C#应用程序相对路径
我刚开始学习C#,看起来当您编写输出文件或读取输入文件时,您需要提供如下绝对路径:C#应用程序相对路径,c#,path,streamreader,streamwriter,C#,Path,Streamreader,Streamwriter,我刚开始学习C#,看起来当您编写输出文件或读取输入文件时,您需要提供如下绝对路径: string[] words = { "Hello", "World", "to", "a", "file", "test" }; using (StreamWriter sw = new StreamWriter(@"C:\Users\jackf_000\Projects\C#\First\First\output.txt")) { for
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时提供绝对目录:
<>我已经用C++和Python编写了,当访问这些语言的文件时,不需要提供绝对目录,只需要从可执行文件/脚本中访问路径即可。每次要读取或写入文件时都必须指定一个绝对路径,这似乎很不方便
是否有任何快速方法可以获取当前目录并将其转换为字符串,将其与outfile字符串名称相结合?使用绝对目录是一种很好的风格,或者如果可能的话,它更倾向于将其与“当前目录”字符串快速组合
谢谢。您不必每次都指定完整目录,相对目录也适用于C#,您可以使用以下方法获取当前目录- 获取应用程序的当前工作目录
string directory = Directory.GetCurrentDirectory();
获取或设置当前工作目录的完全限定路径
string directory = Environment.CurrentDirectory;
获取程序可执行路径
string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
毫无疑问,您不需要指定完整路径,执行此类标准的好方法是什么 应使用相对路径@p.s.w.g,通过注释提及,以使用
目录。GetCurrentDirectory
和路径。合并
还有一些是通过流动的方式指定的
您可以使用System.Reflection.Assembly.getExecutionGassembly().location获取应用程序的.exe
位置。
string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
string exeDir = System.IO.Path.GetDirectoryName(exePath);
DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);
另一方面
在内部,当获取环境.CurrentDirectory
时,它将调用目录.GetCurrentDirectory
,当设置环境.CurrentDirectory
时,它将调用目录.SetCurrentDirectory
只要选一个最喜欢的,就可以了
谢谢欢迎C#我希望它能帮助您向前迈进,而且不需要指定完整路径。相对路径在C#中也起作用。