Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
154 views
in Technique[技术] by (71.8m points)

c# - Relative Paths in Winforms

Relative paths in C# are acting screwy for me. In one case Im handling a set of Texture2d objects to my app, its taking the filename and using this to locate the files and load the textures into Image objects. I then load an image from a relative path stored in the class file and use a relative path that needs to be relative to Content/gfx. But if i dont load these textures these relative paths will fail. How can I garuantee that my rel path wont fail? In web work all rel paths are relative to the folder the file we're working from is in, can I set it up this way and make all rel paths to root folder where my app is located?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

I recommend not using relative paths in the first place.

Use Path.Combine to turn your relative paths into absolute paths. For example, you can use this to get the full path to your startup EXE:

string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;

Once you have that, you can get it's directory:

string exeDir = Path.GetDirectoryName(exeFile);

and turn your relative path to an absolute path:

string fullPath = Path.Combine(exeDir, "..\..\Images\Texture.dds");

This will be much more reliable than trying to use relative paths.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...