C# 应用程序相对路径

C# Application Relative Paths

刚开始学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 编写过,访问这些语言的文件时不需要提供绝对目录,只需提供来自 executable/script 的路径。每次要读取或写入文件时都必须指定绝对路径,这似乎很不方便。

有什么快速的方法可以获取当前目录并将其转换为字符串,并将其与输出文件字符串名称结合起来?使用绝对目录是一种很好的风格,还是首选,如果可能的话,将它与 "current directory" 字符串快速组合?

谢谢。

你不需要每次都指定完整目录,相对目录也适用于C#,你可以使用以下方式获取当前目录-

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

string directory = Directory.GetCurrentDirectory();

获取或设置当前工作目录的完全限定路径。

string directory = Environment.CurrentDirectory;

获取程序可执行路径

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

Resource Link 1 Resource Link 2

大胆地说,你不需要指定完整路径,你执行这种标准的好方法是什么?

should use relative path @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# 我希望它能帮助你前进