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

查看:419
本文介绍了如何获取相对路径中的文件在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

Then use Process.MainModule.FileName:


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

最后,使用 Path.GetDirectoryName 获取文件夹c维护.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天全站免登陆