我刚开始学习 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 编写过,在访问这些语言的文件时不需要提供绝对目录,只需提供可执行文件/脚本的路径。每次要读取或写入文件时都必须指定绝对路径,这似乎很不方便。
有什么快速的方法可以获取当前目录并将其转换为字符串,并将其与输出文件字符串名称结合起来?使用绝对目录是好的风格还是更喜欢,如果可能的话,将它与“当前目录”字符串快速组合?
谢谢。
最佳答案
您不需要每次都指定完整目录,相对目录也适用于 C#,您可以使用以下方式获取当前目录-
获取应用程序的当前工作目录。
string directory = Directory.GetCurrentDirectory();
获取或设置当前工作目录的完全限定路径。
string directory = Environment.CurrentDirectory;
获取程序可执行路径
string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
关于C# 应用程序相对路径,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37041658/