C# 如何在不定义路径的情况下读取现有文本文件

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17405180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:25:14  来源:igfitidea点击:

How to read existing text files without defining path

c#.nettextfile-io

提问by Vilius

Most of the examples shows how to read text file from exact location (f.e. "C:\Users\Owner\Documents\test1.txt"). But, how to read text files without writing full path, so my code would work when copied to other computers. With visual studio I added 2 text files to project (console project) and don't know best way to read those files. Hope I described my problem clearly. Maybe I needed to add those txt files differentely (like directly to same folder as .exe file)?

大多数示例显示了如何从确切位置读取文本文件(fe "C:\Users\Owner\Documents\test1.txt")。但是,如何在不写完整路径的情况下读取文本文件,所以我的代码在复制到其他计算机时可以工作。使用 Visual Studio,我向项目(控制台项目)添加了 2 个文本文件,但不知道读取这些文件的最佳方式。希望我清楚地描述了我的问题。也许我需要以不同的方式添加这些 txt 文件(比如直接添加到与 .exe 文件相同的文件夹中)?

采纳答案by Darren

You could use Directory.GetCurrentDirectory:

你可以使用Directory.GetCurrentDirectory

var path = Path.Combine(Directory.GetCurrentDirectory(), "\fileName.txt");

Which will look for the file fileName.txtin the current directory of the application.

这将fileName.txt在应用程序的当前目录中查找文件。

回答by Dan

When you provide a path, it can be absolute/rooted, or relative. If you provide a relative path, it will be resolved by taking the working directory of the running process.

当您提供路径时,它可以是绝对的/有根的,也可以是相对的。如果您提供相对路径,它将通过获取正在运行的进程的工作目录来解决。

Example:

例子:

string text = File.ReadAllText("Some\Path.txt"); // relative path

The above code has the same effect as the following:

上面的代码和下面的效果一样:

string text = File.ReadAllText(
    Path.Combine(Environment.CurrentDirectory, "Some\Path.txt"));

If you have files that are always going to be in the same location relative to your application, just include a relative path to them, and they should resolve correctly on different computers.

如果您的文件总是位于相对于您的应用程序的相同位置,只需包含它们的相对路径,它们就会在不同的计算机上正确解析。

回答by David Heffernan

You need to decide which directory you want the file to be relative to. Once you have done that, you construct the full path like this:

您需要决定您希望文件相对于哪个目录。完成后,您可以像这样构建完整路径:

string fullPathToFile = Path.Combine(dir, fileName);

If you don't supply the base directory dirthen you will be at the total mercy of whatever happens to the working directory of your process. That is something that can be out of your control. For example, shortcuts to your application may specify it. Using file dialogs can change it.

如果您不提供基本目录,dir那么您将完全受制于进程工作目录中发生的任何事情。这是你无法控制的事情。例如,您的应用程序的快捷方式可能会指定它。使用文件对话框可以改变它。

For a console application it is reasonable to use relative files directly because console applications are designed so that the working directory is a critical input and is a well-defined part of the execution environment. However, for a GUI app that is not the case which is why I recommend you explicitly convert your relative file name to a full absolute path using some well-defined base directory.

对于控制台应用程序,直接使用相关文件是合理的,因为控制台应用程序的设计使得工作目录是关键输入并且是执行环境的明确定义的部分。但是,对于 GUI 应用程序,情况并非如此,这就是为什么我建议您使用一些明确定义的基目录将相对文件名显式转换为完整绝对路径的原因。

Now, since you have a console application, it is reasonable for you to use a relative path, provided that the expectation is that the files in question will be located in the working directory. But it would be very common for that not to be the case. Normally the working directory is used to specify where the user's input and output files are to be stored. It does not typically point to the location where the program's files are.

现在,由于您有一个控制台应用程序,因此使用相对路径是合理的,前提是期望相关文件将位于工作目录中。但情况并非如此是很常见的。通常,工作目录用于指定存储用户输入和输出文件的位置。它通常不指向程序文件所在的位置。

One final option is that you don't attempt to deploy these program files as external text files. Perhaps a better option is to link them to the executable as resources. That way they are bound up with the executable and you can completely side-step this issue.

最后一种选择是不要尝试将这些程序文件部署为外部文本文件。也许更好的选择是将它们作为资源链接到可执行文件。这样它们就与可执行文件绑定在一起,您可以完全回避这个问题。

回答by ElDog

There are many ways to get a path. See CurrentDirrectory mentioned. Also, you can get the full file name of your application by using Assembly.GetExecutingAssembly().Location and then use Path class to get a directory name.

获取路径的方法有很多。请参阅提到的 CurrentDirectory。此外,您可以使用 Assembly.GetExecutingAssembly().Location 获取应用程序的完整文件名,然后使用 Path 类获取目录名。

回答by armitage

As your project is a console project you can pass the path to the text files that you want to read via the string[] args

由于您的项目是一个控制台项目,因此您可以通过 string[] args 将路径传递到要读取的文本文件

static void Main(string[] args)
{
}

Within Main you can check if arguments are passed

在 Main 中,您可以检查是否传递了参数

if (args.Length == 0){ System.Console.WriteLine("Please enter a parameter");}

Extract an argument

提取参数

string fileToRead = args[0];

Nearly all languages support the concept of argument passing and follow similar patterns to C#.

几乎所有语言都支持参数传递的概念,并遵循与 C# 类似的模式。

For more C# specific see http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

有关 C# 的更多信息,请参阅http://msdn.microsoft.com/en-us/library/vstudio/cb20e19t.aspx

回答by JeffRSon

You absolutely need to know where the files to be read can be located. However, this information can be relativeof course so it may be well adapted to other systems.

您绝对需要知道要读取的文件的位置。然而,这些信息当然可以是相对的,因此它可以很好地适应其他系统。

So it could relate to the current directory (get it from Directory.GetCurrentDirectory()) or to the application executable path (eg. Application.ExecutablePathcomes to mind if using Windows Forms or via Assembly.GetEntryAssembly().Location) or to some special Windows directory like "Documents and Settings" (you should use Environment.GetFolderPath()with one element of the Environment.SpecialFolderenumeration).

因此,它可能涉及到当前目录(从得到它Directory.GetCurrentDirectory())或应用程序可执行文件路径(例如,Application.ExecutablePath想到如果使用Windows窗体或通过Assembly.GetEntryAssembly().Location)或一些特殊的Windows目录下,如“文件和设置”(你应该使用Environment.GetFolderPath()一个Environment.SpecialFolder枚举元素)。

Note that the "current directory" and the path of the executable are not necessarily identical. You need to know where to look!

请注意,“当前目录”和可执行文件的路径不一定相同。你需要知道去哪里找!

In either case, if you need to manipulate a path use the Path class to split or combine parts of the path.

在任何一种情况下,如果您需要操作路径,请使用 Path 类来拆分或组合路径的各个部分。

回答by terrybozzio

This will load a file in working directory:

这将在工作目录中加载一个文件:

        static void Main(string[] args)
        {
            string fileName = System.IO.Path.GetFullPath(Directory.GetCurrentDirectory() + @"\Yourfile.txt");

            Console.WriteLine("Your file content is:");
            using (StreamReader sr = File.OpenText(fileName))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }

            Console.ReadKey();
        }

If your using console you can also do this.It will prompt the user to write the path of the file(including filename with extension).

如果您使用控制台,您也可以这样做。它会提示用户写入文件的路径(包括文件名和扩展名)。

        static void Main(string[] args)
        {

            Console.WriteLine("****please enter path to your file****");
            Console.Write("Path: ");
            string pth = Console.ReadLine();
            Console.WriteLine();
            Console.WriteLine("Your file content is:");
            using (StreamReader sr = File.OpenText(pth))
            {
                string s = "";
                while ((s = sr.ReadLine()) != null)
                {
                    Console.WriteLine(s);
                }
            }

            Console.ReadKey();
        }

If you use winforms for example try this simple example:

例如,如果您使用 winforms,请尝试以下简单示例:

        private void button1_Click(object sender, EventArgs e)
        {
            string pth = "";
            OpenFileDialog ofd = new OpenFileDialog();

            if (ofd.ShowDialog() == DialogResult.OK)
            {
                pth = ofd.FileName;
                textBox1.Text = File.ReadAllText(pth);
            }
        }

回答by AXMIM

If your application is a web service, Directory.CurrentDirectorydoesn't work.

如果您的应用程序是 Web 服务,Directory.CurrentDirectory则不起作用。

Use System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt"))instead.

使用System.IO.Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "yourFileName.txt"))来代替。