StreamReader 不接受字符串参数?
StreamReader not accept string arguments?
通过 VScode 使用 dotnet-cli(dotnet new、dotnet restore),我制作了一个新的 C# 程序。
但是,我似乎无法正确使用 StreamReader。这是代码。
using System;
using System.IO;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
StreamReader test = new StreamReader("Test.txt");
}
}
}
我似乎无法 运行 这个程序。当我 运行 使用
dotnet 运行,它说
'string' cannot be converted to 'System.IO.Stream' [netcoreapp1.0]
我尝试在 Visual Studio 社区中创建相同的程序,它 运行 没有任何错误
要解决您的问题:您必须使用 Stream 作为对文件的基本访问:
using(var fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read))
using (var sr = new System.IO.StreamReader(fs)){
//Read file via sr.Read(), sr.ReadLine, ...
}
}
由于 StreamReader
和 FileStream
实现了 IDisposable
,它们将因 using 子句而被处理掉,因此您无需编写调用 .Close()
或.Dispose()
(正如@TaW 所说)。
通过 VScode 使用 dotnet-cli(dotnet new、dotnet restore),我制作了一个新的 C# 程序。
但是,我似乎无法正确使用 StreamReader。这是代码。
using System;
using System.IO;
namespace ConsoleApplication
{
public class Program
{
public static void Main(string[] args)
{
StreamReader test = new StreamReader("Test.txt");
}
}
}
我似乎无法 运行 这个程序。当我 运行 使用 dotnet 运行,它说
'string' cannot be converted to 'System.IO.Stream' [netcoreapp1.0]
我尝试在 Visual Studio 社区中创建相同的程序,它 运行 没有任何错误
要解决您的问题:您必须使用 Stream 作为对文件的基本访问:
using(var fs = new FileStream("file.txt", FileMode.Open, FileAccess.Read))
using (var sr = new System.IO.StreamReader(fs)){
//Read file via sr.Read(), sr.ReadLine, ...
}
}
由于 StreamReader
和 FileStream
实现了 IDisposable
,它们将因 using 子句而被处理掉,因此您无需编写调用 .Close()
或.Dispose()
(正如@TaW 所说)。