StreamWriter和StreamReader无法正常工作
我一直试图了解几个小时,为什么我的项目(完整桌面应用程序)不会让我以适当的方式使用StreamWriter或StreamReader。问题是,如果我尝试给任的StreamWriter或StreamReader的文件路径(只是一个简单的字符串),如下图所示...StreamWriter和StreamReader无法正常工作
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;
}
编辑:运行上面的代码试图让所有的红线消失将会在这篇文章中发布错误。
下面是它目前看起来像(错误)
以上就是它应该是什么样子的(正确的 - 与路径放慢参数)
文档: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个类库(SO 2个项目1个解决方案,我想会是正确的说?),它非常有效。我这样做是因为我的另一个解决方案由3个类库组成,所以我认为如果可以的话,在再现问题时保持一致性是一个好主意。所以,我创建了一个简单的文本文件,用一些文本填充它,并将其作为新解决方案中TextBox中的屏幕输出。这基本上让我不知道现在该做什么。
有谁知道什么可能会导致此问题?
很简单,您所针对的.Net版本(.Net Standard 1.4)中的StreamReader
类不支持具有文件路径的构造函数。
您需要使用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());
}
}
}
基础上的评论,在当前的.NET的StreamReader
没有适当的过载,可以采取文件的路径。您可以使用其他替代方法。您可以使用FileStream
打开您想要的文件,然后使用StreamReader
进行阅读。
这是一个什么样的项目,它是一个完整的桌面应用程序,或者这是一个应用程序商店应用程序或电话应用程序? –
请将您的代码和错误消息作为文本发布,而不是截图。也就是说,你提到了“一个filePath(只是一个简单的字符串)” - 你能给出一些关于字符串的复杂性的例子,你担心会导致StreamReader的问题? –
什么.net框架是您的项目定位?看看项目属性。 – Igor