如何在C#中的相对路径中获取文件

Joa*_*nge 30 .net c# directory file

如果我有一个名为app.exe的可执行文件,这是我在C#中编码的,我如何使用相对路径从与app.exe相同的目录中加载文件夹?

这会在路径异常中抛出非法字符:

string [ ] files = Directory.GetFiles ( "\\Archive\\*.zip" );
Run Code Online (Sandbox Code Playgroud)

如何在C#中做到这一点?

Kie*_*one 41

要确保您拥有应用程序的路径(而不仅仅是当前目录),请使用以下命令:

http://msdn.microsoft.com/en-us/library/system.diagnostics.process.getcurrentprocess.aspx

现在您有一个Process表示正在运行的进程的对象.

然后使用Process.MainModule.FileName:

http://msdn.microsoft.com/en-us/library/system.diagnostics.processmodule.filename.aspx

最后,使用Path.GetDirectoryName获取包含.exe的文件夹:

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);
Run Code Online (Sandbox Code Playgroud)

(请注意,"\Archive\"现在你的问题是@"\Archive\":你需要@这样\反斜杠不被解释为转义序列的开始)

希望有所帮助!

  • Path.GetDirectoryName(Assembly.GetEntryAssembly()的位置.); 更简单的imo. (7认同)

Ada*_*ear 30

string currentDirectory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
string archiveFolder = Path.Combine(currentDirectory, "archive");
string[] files = Directory.GetFiles(archiveFolder, "*.zip");
Run Code Online (Sandbox Code Playgroud)

第一个参数是路径.第二个是您要使用的搜索模式.


Mik*_*son 16

写这样:

string[] files = Directory.GetFiles(@".\Archive", "*.zip");
Run Code Online (Sandbox Code Playgroud)

.是相对于您启动exe的文件夹,@是允许在名称中的\.

使用过滤器时,将其作为第二个参数传递.您还可以添加第三个参数以指定是否要递归搜索模式.

要获取.exe实际所在的文件夹,请使用:

var executingPath = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Run Code Online (Sandbox Code Playgroud)