在c#中将大量行保存到文本文件的最快方法

时间:2015-05-09 08:55:15

标签: c# save

我目前正在编写一个程序,需要将多兆字节的数据保存到文本文件中。

该数据保存在字符串中     <列表>

我当前的代码(allusernames是列表变量名称)

      string alltoappend = "";
        string speichern = "C:\\Users\\" + Environment.UserName + "\\Desktop\\scraped.txt";
        progressBarSetValue(progressBar1, 100);
        MessageBox.Show("Done scraping!\nNow saving all the usernames to:\n" + speichern + "\nThis might take a while");
        foreach (string linelist in allusernames)
        {

            alltoappend = alltoappend + "\n" + linelist;
        }

        File.AppendAllText(speichern, alltoappend, Encoding.UTF8);



        System.Diagnostics.Process.Start(speichern);
        allusernames.Clear();

可能需要几分钟才能保存数兆字节的数据,这是不必要的。

有更快的方法吗?我听到了人们的一些.join()建议,但我不知道如何使用它。

非常感谢

1 个答案:

答案 0 :(得分:3)

使用StringBuilder:

org.hsql.jdbcDriver

您也可以直接写入文件:

StringBuilder sb = new StringBuilder();
foreach (string line in allusernames)
{
    sb.AppendLine(line);
}
string result = sb.ToString();

并且不要像现在这样使用路径。

错:

using (var stream = File.OpenWrite(filename))
{
    using (var writer = new StreamWriter(stream))
    {
        foreach (string line in allusernames)
        {
            writer.WriteLine(line);
        }
    }
}

右:

string speichern = "C:\\Users\\" + Environment.UserName + "\\Desktop\\scraped.txt";

最好的:

string speichern = Path.Combine("C:\\Users", Environment.UserName , "Desktop\\scraped.txt");