【发布时间】:2016-08-30 17:07:44
【问题描述】:
我刚开始学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 编写过,在访问这些语言的文件时,您不需要提供绝对目录,只需提供可执行文件/脚本的路径即可。每次要读取或写入文件时都必须指定绝对路径似乎很不方便。
有什么快速的方法来获取当前目录并将其转换为字符串,将其与 outfile 字符串名称相结合?使用绝对目录是一种好的风格还是首选,如果可能的话,快速将它与“当前目录”字符串结合起来?
谢谢。
【问题讨论】:
-
Directory.GetCurrentDirectory和Path.Combine- 不,您不必指定完整路径。相对路径也适用于 C#。
标签: c# path streamreader streamwriter