950ko后文件写入不成功

时间:2012-07-09 23:30:51

标签: c#

我刚回到c#为我的一个项目创建了一个csv到sql的翻译器。 然而,我遇到了一个奇怪的行为,我的谷歌搜索没有成功,所以我需要你的帮助。

这是以下代码(适合场合,不是我的质量差,我不是csharp专家)

string line, generated;
System.IO.FileStream fs = new System.IO.FileStream("data.sql", System.IO.FileMode.Create);
System.IO.StreamWriter w = new System.IO.StreamWriter(fs, Encoding.UTF8);
System.IO.StreamReader file = new System.IO.StreamReader("source.txt", System.Text.Encoding.UTF8);
while ((line = file.ReadLine()) != null)
        {
            String[] ar = line.Split('|');
            generated = "INSERT INTO `translation` VALUES('" + ar[0] + "'," + ar[1] + ");";
            w.WriteLine(generated);
        }
// Closing file stuff

该文件已成功创建,并为小文件生成了大量文件。但是,当我在大文件上使用它时,生成的文件被截断(始终在同一个地方,结果文件为950ko~)

结果是这样的

INSERT INTO `translation` VALUES ( 'trans1', 1 );
INSERT INTO `translation` VALUES ( 'trans2', 2 );
INSERT INTO `translation` VALUES ( 'trans3', 3 );
INSERT INTO `tran

我想念6行。 因此,如果有人有了一个想法,我会热切地倾听

PS:我可以通过分块我的源文件轻松解决这个问题,但是我对这个问题很好奇并且不能认为它是.Net问题,我一定做错了。

关心所有

结束的东西

w.Close();
file.Close();
fs.Close();

编辑:解决方案 根据人们的建议,解决我的问题的方法如下:

// Replacing my FileStream and StreamWriter by the following line
System.IO.StreamWriter w = new System.IO.StreamWriter("data.sql", false, System.Text.Encoding.UTF8);
// Removing the fs.Close()

它现在像一个魅力。我可以通过使用'using'关键字来避免调用Close函数(就像Mehrdad所说)但我不想添加额外的{}(我的口味)

谢谢大家

3 个答案:

答案 0 :(得分:1)

我的问题的解决方案是:

string line, generated;
using(System.IO.StreamReader file = new System.IO.StreamReader("source.txt", System.Text.Encoding.UTF8)){
   using(System.IO.StreamWriter w = new System.IO.StreamWriter("data.sql", false, System.Text.Encoding.UTF8)){
     while ((line = file.ReadLine()) != null)
       {
        String[] ar = line.Split('|');
        generated = "INSERT INTO `translation` VALUES('" + ar[0] + "'," + ar[1] + ");";
        w.WriteLine(generated);
       }
    }
}

答案 1 :(得分:0)

您确定按此顺序关闭wfs(即按照与打开时相反的顺序)吗?

答案 2 :(得分:0)

请确保Flush StreamWriter之前“关闭文件”。