如何获得在C#中的相对路径文件 [英] How to get files in a relative path in C#
问题描述
如果我有一个叫做APP.EXE一个可执行这就是我编码在C#中,我将如何获取文件从同一目录中APP.EXE加载一个文件夹,使用相对路径?
If I have an executable called app.exe which is what I am coding in C#, how would I get files from a folder loaded in the same directory as the app.exe, using relative paths?
这将引发非法字符的路径异常:
This throws an illegal characters in path exception:
string [ ] files = Directory.GetFiles ( "\\Archive\\*.zip" );
在C#中一个人怎么会这样?
How would one do this in C#?
推荐答案
要确保你的应用程序的路径(而不仅仅是当前目录),使用:
To make sure you have the application's path (and not just the current directory), use this:
<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx">http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx
现在你有一个进程
对象重新presents正在运行的进程。
Now you have a Process
object that represents the process that is running.
然后使用 Process.MainModule.FileName
:
<一个href="http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx">http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx
最后,使用 Path.GetDirectoryName
获得包含.exe的文件夹:
Finally, use Path.GetDirectoryName
to get the folder containing the .exe:
<一个href="http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx">http://msdn.microsoft.com/en-us/library/system.io.path.getdirectoryname.aspx
这就是你想要的:
string folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + @"\Archive\";
string filter = "*.zip";
string[] files = Directory.GetFiles(folder, filter);
(注意,\存档\
从你的问题现在是 @\存档\
:您需要@,使 \
反斜杠不是PTED作为转义序列的开始跨$ P $)
(Notice that "\Archive\"
from your question is now @"\Archive\"
: you need the @ so that the \
backslashes aren't interpreted as the start of an escape sequence)
希望帮助!
这篇关于如何获得在C#中的相对路径文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!