我如何从文件中读取?

时间:2013-10-08 19:25:38

标签: c# .net file-io cmd

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

6 个答案:

答案 0 :(得分: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());
}

答案 1 :(得分: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!");

答案 2 :(得分: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();
}

答案 3 :(得分:1)

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

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

答案 4 :(得分:0)

using(var fs = new FileStream(winDir + "\\Name.txt", FileMode.Open, FileAccess.Read))
{
    using(var reader = new  StreamReader(fs))
    {
        // your code
    }
}

答案 5 :(得分: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加载到内存中是一种偏执。

相关问题