-1

我试图让我的程序从 .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();
    }
}
4

6 回答 6

3

如果您的文件与 位于同一文件夹中.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());
}
于 2013-10-08T19:28:21.027 回答
3

我不喜欢您的解决方案,原因有两个:

1)我不喜欢把所有的东西都洗掉(试着抓住)。为了避免使用检查文件是否存在System.IO.File.Exist("YourPath")

2)使用此代码,您没有处理流式阅读器。为了避免这种情况,最好使用 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!");
于 2013-10-08T19:39:05.743 回答
1

为什么不使用 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();
}
于 2013-10-08T19:27:12.403 回答
1

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

File.ReadAllText(Path.Combine(winDir, "Name.txt"));
于 2013-10-08T19:28:58.157 回答
0
using(var fs = new FileStream(winDir + "\\Name.txt", FileMode.Open, FileAccess.Read))
{
    using(var reader = new  StreamReader(fs))
    {
        // your code
    }
}
于 2013-10-08T19:34:45.300 回答
0

.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到内存中。

于 2013-10-08T19:45:04.737 回答