Jac*_*rye 4 c# path streamwriter streamreader
我刚开始学习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();
}
Run Code Online (Sandbox Code Playgroud)
MSDN 的示例使您在实例化 StreamWriter 时看起来需要提供绝对目录:
https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx
我用 C++ 和 Python 编写过,在访问这些语言的文件时不需要提供绝对目录,只需提供可执行文件/脚本的路径。每次要读取或写入文件时都必须指定绝对路径似乎很不方便。
有没有什么快速的方法可以抓取当前目录并将其转换为字符串,并将其与输出文件字符串名称结合起来?使用绝对目录是一种很好的风格还是更喜欢,如果可能的话,快速将它与“当前目录”字符串结合起来?
谢谢。
您不需要每次都指定完整目录,相对目录也适用于 C#,您可以使用以下方式获取当前目录 -
获取应用程序的当前工作目录。
string directory = Directory.GetCurrentDirectory();
Run Code Online (Sandbox Code Playgroud)
获取或设置当前工作目录的完全限定路径。
string directory = Environment.CurrentDirectory;
Run Code Online (Sandbox Code Playgroud)
获取程序可执行路径
string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11927 次 |
| 最近记录: |