我刚开始学习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编写,这两种语言在访问文件时不需要提供绝对目录,只需提供可执行文件/脚本的路径。每次想要读写文件都指定绝对路径似乎很麻烦。
有没有快速获取当前目录并将其转换为字符串,将其与输出文件名组合?使用绝对目录好还是如果可能的话,快速结合“当前目录”字符串更好呢?
谢谢。
Directory.GetCurrentDirectory
和Path.Combine
--你不需要指定完整路径。相对路径在C#中也可以使用。 - p.s.w.g