我正在尝试使用OpenRead
方法并遇到下面显示的错误,我在代码和参考文献中添加了using.system.IO
,如下面的屏幕截图所示?我错过了什么?如何摆脱这个错误?
using System;
using System.IO;
var zipFileName = @"C:\Temp\bins-9111.tar.bz2";
using (FileStream fileToDecompressAsStream = zipFileName.OpenRead())
{
string decompressedFileName = @"c:\bzip2\decompressed.txt";
using (FileStream decompressedStream = File.Create(decompressedFileName))
{
try
{
BZip2.Decompress(fileToDecompressAsStream, decompressedStream, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
错误: -
'string' does not contain a definition for 'OpenRead' and no extension method 'OpenRead' accepting a first argument of type 'string' could be found (are you missing a using directive or an assembly reference?) ConsoleApplication2 c:\users\gnakkala\documents\visual studio 2015\Projects\ConsoleApplication2\ConsoleApplication2\Program.cs 32
答案 0 :(得分:2)
您正在尝试在字符串对象上调用System.IO.File方法。 试试这个: 我将对OpenRead的调用更改为来自File Object而不是string。
var zipFileName = @"C:\Temp\bins-9111.tar.bz2";
using (System.IO.FileStream fs = System.IO.File.OpenRead(zipFileName))
{
string decompressedFileName = @"c:\bzip2\decompressed.txt";
using (FileStream decompressedStream = File.Create(decompressedFileName))
{
try
{
BZip2.Decompress(fileToDecompressAsStream, decompressedStream, true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
答案 1 :(得分:2)
正如@Shannon Holsinger
在评论中提到的"Safe assignment in condition"是OpenRead上的静态方法,而不是字符串。
var zipFileName = @"C:\Temp\bins-9111.tar.bz2";
using (FileStream fileToDecompressAsStream = System.IO.File.OpenRead(zipFileName))
{/* rest of code */}
有关详细信息,请参阅System.IO.File文档。