如何解决StreamWriter错误“无法将类型字符串隐式转换为System.IO.StreamWriter”

时间:2019-10-16 09:04:52

标签: c# streamwriter

我在Visual Studio 2017社区中使用C#。

我有一个正在运行的功能齐全的程序,我正在尝试对其进行优化。简而言之,该程序从文本文件中读取文本和数字,进行一些数学运算和重新格式化,然后输出到新的文本文件。

我要优化的部分是将文本行写入输出文件的方式。这是有效的方法:

using System.IO

// Let's start building the MA output text file now.
// Designate an output file --- put it in same directory as original files
// give MA file ame name as the original file -- but different extension.

maOutFile = dir + "\\" + serialNumber[f] + ".ma";

//Create MA header lines and write to file.

string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";

// Open up the file for writing
File.WriteAllText(maOutFile, maHeaderLine1);
File.AppendAllText(maOutFile, maHeaderLine2);

上面的代码工作正常。我担心的是效率不是很高,尤其是在网络速度较慢的情况下。每次写入文件时都会打开和关闭文件。

因此,为了使运行速度更快,我想我会尝试StreamWriter。

我的StreamWriter代码如下:


// Designate an output file --- put it in same directory as the original files
// give MA file same name as the original file -- with different extension.

// maOutFile = dir + "\\" + serialNumber[f] + ".ma";

StreamWriter outfile;
outfile = dir + "\\" + serialNumber[f] + ".ma";

//Create MA header lines and write to file.

string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";

// Open up the file for writing
//File.WriteAllText(maOutFile, maHeaderLine1);
//File.AppendAllText(maOutFile, maHeaderLine2);
outfile.WriteLine(maHeaderLine1);
outfile.WriteLine(maHeaderLine2);

Visual Studio不喜欢使用StreamWriter的新代码。它在“ outfile = dir +“ \” + serialNumber [f] +“ .ma”;行的等号右边的所有内容下方放置一条红线。

当我将鼠标悬停在红线代码上时,消息为“无法将类型字符串隐式转换为System.IO.StreamWriter”。

我的新代码不怎么样?

3 个答案:

答案 0 :(得分:1)

您正在将字符串变量分配给StreamWriter对象,而不是创建StreamWriter对象。

尝试以下

using (StreamWriter sw = new StreamWriter(dir + "\\" + serialNumber[f] + ".ma"))
{
string maHeaderLine1 = "TITLE: S/N:" + serialNumber[f] + "\n";
string maHeaderLine2 = "ENGLISH(IN)/METRIC(MM) INDICATOR :IN-P\n";

// Open up the file for writing
//File.WriteAllText(maOutFile, maHeaderLine1);

sw.WriteLine(maHeaderLine1);
sw.WriteLine(maHeaderLine2);
}

答案 1 :(得分:0)

您要在此处为​​StreamWriter分配一个字符串:

outfile = dir + "\\" + serialNumber[f] + ".ma";

并查看您试图以流形式打开文件的代码,类似以下内容:

string outFileDir = dir + "\\" + serialNumber[f] + ".ma";
StreamWriter outFile = new StreamWriter(outFileDir);

答案 2 :(得分:0)

console.log('done.')

}