如何在C#中获取相对路径中的文件 [英] How to get files in a relative path in C#

查看:116
本文介绍了如何在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:

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

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

Now you have a Process object that represents the process that is running.

然后使用Process.MainModule.FileName:

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:

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);

(注意您问题中的 "Archive" 现在是 @"Archive":您需要 @ 以便 代码> 反斜杠不被解释为转义序列的开始)

(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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆