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

编程入门 行业动态 更新时间:2024-10-09 18:22:46
本文介绍了如何获取相对路径中的文件在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:

msdn.microsoft /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:

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

最后,使用 Path.GetDirectoryName 获取文件夹c维护.exe:

Finally, use Path.GetDirectoryName to get the folder containing the .exe:

msdn.microsoft/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#

本文发布于:2023-05-31 14:01:52,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/393039.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:路径   文件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!