StreamWriter和StreamReader无法正常工作

时间:2017-10-20 15:04:56

标签: c# wpf streamreader

我一直试图理解为什么我的项目(完整的桌面应用程序)不允许我以正确的方式使用StreamWriter或StreamReader。问题是,如果我尝试给StreamWriter或StreamReader一个filePath(只是一个简单的字符串),如下所示...

private readonly string _filePath = @"...Text.txt";

public string TestMethod(string text)
{    
        // Does not accept a string as an argument, which it should based on the documentation
        StreamReader reader = new StreamReader();
        text = reader.ReadToEnd();
        reader.Close();

        return text;
}

编辑:运行上面的代码试图让所有红线都消失,这将是本帖后面发布的错误。

以下是目前的样子(错误)

Wrong

Correct

上面是它的样子(正确 - 用路径参数)

文档:https://msdn.microsoft.com/en-us/library/f2ke0fzy(v=vs.110).aspx

...我在整个地方都遇到错误,如果我尝试以另一种方式给它提供其他参数,我会收到错误说:

System.IO.FileNotFoundException: 'Could not load file or assembly 'System.Console, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a' or one of its dependencies. The system cannot find the file specified.'

我试图创建一个全新的解决方案,它包含2个类库(所以2个项目用于1个解决方案,我想这是正确的说法吗?)并且它几乎可以工作。我这样做是因为我的另一个解决方案包含3个类库,所以我认为如果可以的话,在重现问题时保持一致是个好主意。因此,我创建了一个简单的文本文件,用一些文本填充它,并在新解决方案的TextBox中将其作为输出显示在屏幕上。这基本上让我不知道现在该做什么。

有人知道可能导致此问题的原因吗?

2 个答案:

答案 0 :(得分:2)

很简单,您所针对的.Net版本中的StreamReader类(.Net Standard 1.4)不支持采用文件路径的构造函数。

您需要使用FileStream类打开文件,然后使用StreamReader来读取文件。

以下是从文档中复制的示例:

https://docs.microsoft.com/en-us/dotnet/api/system.io.streamreader.-ctor?view=netstandard-1.4

using System;
using System.IO;

class Test 
{

    public static void Main() 
    {
        string path = @"c:\temp\MyTest.txt";

        try 
        {
            if (File.Exists(path)) 
            {
                File.Delete(path);
            }

            using (StreamWriter sw = new StreamWriter(path)) 
            {
                sw.WriteLine("This");
                sw.WriteLine("is some text");
                sw.WriteLine("to test");
                sw.WriteLine("Reading");
            }

            using (FileStream fs = new FileStream(path, FileMode.Open)) 
            {
                using (StreamReader sr = new StreamReader(fs)) 
                {

                    while (sr.Peek() >= 0) 
                    {
                        Console.WriteLine(sr.ReadLine());
                    }
                }
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

答案 1 :(得分:0)

根据评论,当前.NET中的log4j: *log4j configuration steps, going through the properties file* Starting Project Driver 没有适当的重载,可以采用文件路径。您可以使用其他替代方法。您可以使用StreamReader打开所需的文件,然后使用FileStream进行阅读。