【问题标题】:C# Application Relative PathsC# 应用程序相对路径
【发布时间】: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 字符串名称相结合?使用绝对目录是一种好的风格还是首选,如果可能的话,快速将它与“当前目录”字符串结合起来?

谢谢。

【问题讨论】:

标签: c# path streamreader streamwriter


【解决方案1】:

您不需要每次都指定完整目录,相对目录也适用于C#,您可以使用以下方式获取当前目录-

获取应用程序的当前工作目录。

string directory = Directory.GetCurrentDirectory();

获取或设置当前工作目录的完全限定路径。

string directory = Environment.CurrentDirectory;

获取程序可执行路径

string directory = System.IO.Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);

Resource Link 1Resource Link 2

【讨论】:

    【解决方案2】:

    当然,您无需指定完整路径,您执行此类标准的好方法是什么?

    应该使用相对路径@p.s.w.g 已经通过评论提及使用Directory.GetCurrentDirectory 和Path.Combine

    还有一些通过流动方式指定

    您可以使用System.Reflection.Assembly.GetExecutingAssembly().Location. 获取应用的.exe 位置

    string exePath = System.Reflection.Assembly.GetExecutingAssembly().Location;
    string exeDir = System.IO.Path.GetDirectoryName(exePath);
    DirectoryInfo binDir = System.IO.Directory.GetParent(exeDir);
    

    另一方面 在内部,当获取Environment.CurrentDirectory 时,它将调用Directory.GetCurrentDirectory,当设置Environment.CurrentDirectory 时,它将调用Directory.SetCurrentDirectory。

    只需选择一个最喜欢的并使用它。

    谢谢你欢迎 C# 我希望它能帮助你前进

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2013-06-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多