如何从文件中读取

本文关键字:读取 文件 | 更新日期: 2023-09-27 18:34:23

我试图让我的程序从.txt读取代码,然后将其读回给我,但由于某种原因,它在我编译时使程序崩溃。有人可以让我知道我做错了什么吗?谢谢!:)

using System;
using System.IO;
public class Hello1
{
    public static void Main()
    {   
        string    winDir=System.Environment.GetEnvironmentVariable("windir");
        StreamReader reader=new  StreamReader(winDir + "''Name.txt");
            try {      
            do {
                        Console.WriteLine(reader.ReadLine());
            }   
            while(reader.Peek() != -1);
            }      
            catch 
            { 
            Console.WriteLine("File is empty");
            }
            finally
            {
            reader.Close();
            }
    Console.ReadLine();
    }
}

如何从文件中读取

我不喜欢你的解决方案,原因很简单:

1)我不喜欢所有Cath 'em(尝试捕捉)。对于 avoing,请使用 System.IO.File.Exist("YourPath") 检查文件是否存在

2)使用此代码,尚未释放流读取器。对于 avo,最好使用 using 构造函数,如下所示:using(StreamReader sr=new StreamReader(path)){ //Your code}

使用示例:

        string path="filePath";
        if (System.IO.File.Exists(path))
            using (System.IO.StreamReader sr = new System.IO.StreamReader(path))
            {
                while (sr.Peek() > -1)
                    Console.WriteLine(sr.ReadLine());
            }
        else
            Console.WriteLine("The file not exist!");

如果您的文件与.exe位于同一文件夹中,您需要做的就是StreamReader reader = new StreamReader("File.txt");

否则,在 File.txt 所在的位置,放置文件的完整路径。就个人而言,我认为如果他们在同一个位置会更容易。

从那里开始,就像Console.WriteLine(reader.ReadLine());一样简单

如果你想读取所有行并一次显示所有行,你可以做一个for循环:

for (int i = 0; i < lineAmount; i++)
{
    Console.WriteLine(reader.ReadLine());
}

如果您希望结果为字符串而不是数组,请使用下面的代码。

File.ReadAllText(Path.Combine(winDir, "Name.txt"));

为什么不使用 System.IO.File.ReadAllLines(winDir + "''Name.txt")

如果您要做的就是在控制台中将其显示为输出,则可以非常紧凑地执行此操作:

private static string winDir = Environment.GetEnvironmentVariable("windir");
static void Main(string[] args)
{
    Console.Write(File.ReadAllText(Path.Combine(winDir, "Name.txt")));
    Console.Read();
}
using(var fs = new FileStream(winDir + "''Name.txt", FileMode.Open, FileAccess.Read))
{
    using(var reader = new  StreamReader(fs))
    {
        // your code
    }
}

.NET 框架有多种读取文本文件的方法。 每个都有优点和缺点...让我们经历两个。

第一个,是许多其他答案推荐的答案:

String allTxt = File.ReadAllText(Path.Combine(winDir, "Name.txt"));

这会将整个文件读入单个String。它将是快速和无痛的。不过它有风险...如果文件足够大,则可能会耗尽内存。 即使你可以将整个东西存储到内存中,它也可能足够大,你会有分页,并且会使你的软件运行得很慢。 下一个选项可解决此问题。

第二种解决方案允许您一次使用一行,而不是将整个文件加载到内存中:

foreach(String line in File.ReadLines(Path.Combine(winDir, "Name.txt")))
  // Do Work with the single line.
  Console.WriteLine(line);

对于文件,此解决方案可能需要更长的时间,因为它会更频繁地处理文件的内容......但是,它将防止尴尬的内存错误。

我倾向于使用第二种解决方案,但这只是因为我偏执地将大量Strings加载到内存中。