C# 应用程序相对路径 [英] C# Application Relative Paths

查看:58
本文介绍了C# 应用程序相对路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学C#,貌似在写输出文件或者读输入文件的时候,需要提供如下的绝对路径:

I just started learning C# and it looks like when you are writing an output file or reading an input file, you need to provide the absolute path such as follows:

        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 时看起来需要提供绝对目录:

MSDN's examples make it look like you need to provide the absolute directory when instantiating a StreamWriter:

https://msdn.microsoft.com/en-us/library/8bh11f1k.aspx

我用 C++ 和 Python 编写过,访问这些语言的文件时不需要提供绝对目录,只需提供可执行文件/脚本的路径即可.每次要读取或写入文件时都必须指定绝对路径似乎很不方便.

I have written in both C++ and Python and you do not need to provide the absolute directory when accessing files in those languages, just the path from the executable/script. It seems like an inconvenience to have to specify an absolute path every time you want to read or write a file.

有没有什么快速的方法可以抓取当前目录并将其转换为字符串,并将其与输出文件字符串名称组合?使用绝对目录是一种很好的风格还是更喜欢,如果可能的话,快速将它与当前目录"字符串结合起来?

Is there any quick way to grab the current directory and convert it to a string, combining it with the outfile string name? And is it good style to use the absolute directory or is it preferred to, if it's possible, quickly combine it with the "current directory" string?

谢谢.

推荐答案

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

You don't need to specify full directory everytime, relative directory also work for C#, you can get current directory using following way-

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

Gets the current working directory of the application.

string directory = Directory.GetCurrentDirectory();

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

Gets or sets the fully qualified path of the current working directory.

string directory = Environment.CurrentDirectory;

获取程序可执行路径

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

资源链接 1 资源链接 2

这篇关于C# 应用程序相对路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆