C#应用程序相对路径

5

我刚开始学习C#,看起来当你编写输出文件或读取输入文件时,需要提供绝对路径,如下所示:

        string[] words = { "Hello", "World", "to", "a", "file", "test" };
        using (StreamWriter sw = new StreamWriter(@"C:\Users\jackf_000\Projects\C#\First\First\output.txt"))
        {
            foreach (string word in words)
            {
                sw.WriteLine(word);
            }
            sw.Close();
        }

MSDN的示例让人觉得在实例化StreamWriter时需要提供绝对目录:

https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

我用过C++和Python编写,这两种语言在访问文件时不需要提供绝对目录,只需提供可执行文件/脚本的路径。每次想要读写文件都指定绝对路径似乎很麻烦。

有没有快速获取当前目录并将其转换为字符串,将其与输出文件名组合?使用绝对目录好还是如果可能的话,快速结合“当前目录”字符串更好呢?

谢谢。


1
Directory.GetCurrentDirectoryPath.Combine--你不需要指定完整路径。相对路径在C#中也可以使用。 - p.s.w.g
2个回答

12

在C#中,您不需要每次指定完整的目录路径,相对路径也可以工作。您可以使用以下方式获取当前目录 -

获取应用程序的当前工作目录。

string directory = Directory.GetCurrentDirectory();
获取或设置当前工作目录的完全限定路径。
string directory = Environment.CurrentDirectory;

获取程序可执行文件路径

string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

资源链接1 资源链接2


1

你无需明确指定完整路径,有什么好的方法可以执行此类条件?

应该使用相对路径,如 @p.s.w.g 在评论中提到的那样,使用 Directory.GetCurrentDirectoryPath.Combine

还可以通过以下方式进行更多的指定:

您可以使用 System.Reflection.Assembly.GetExecutingAssembly().Location 获取应用程序的 .exe 位置。

string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);

另一方面,当获取 Environment.CurrentDirectory 时,它会调用 Directory.GetCurrentDirectory,而当设置 Environment.CurrentDirectory 时,它会调用 Directory.SetCurrentDirectory
只需选择一个喜欢的并使用它即可。
谢谢,欢迎使用 C#,我希望它能帮助您前进。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接