写入新行时的C#字符计数器

时间:2010-05-25 21:23:04

标签: c#

基本上我正在尝试阅读一个非常大的文本文件,当该行的字符达到X量时写入一个新行,但我似乎无法使字符计数起作用。任何帮助表示赞赏!

using (FileStream fs = new FileStream(betaFilePath,FileMode.Open))
    using (StreamReader rdr = new StreamReader(fs))
    {
        while (!rdr.EndOfStream)
        {
            string betaFileLine = rdr.ReadLine();
            int stringline = 0;
            if (betaFileLine.Contains("þTEMP"))
            {
                //sb.AppendLine(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD2.DAT");
                string checkline = betaFileLine.Length.ToString();
                foreach (string cl in checkline)
                {
                    stringline++;
                    File.AppendAllText(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD3.DAT", cl);
                    if(stringline == 1200)
                    {
                        File.AppendAllText(@"C:\chawkster\workfiles\New Folder\GEL_ALL_PRODUCTS_CONCORD3.DAT","\n");
                        stringline = 0;
                    }
                }                           
            }
        }

错误:

foreach (string cl in checkline)
Error   1   Cannot convert type 'char' to 'string'  

3 个答案:

答案 0 :(得分:1)

我不明白为什么你有string checkline = betaFileLine.Length.ToString();,因为那只会占用当前行并给你一个字符串格式的数字长度。你不想要当前行中的所有字符吗?不确定你想要的数字长度。

不确定你在做什么,但尝试:

// Get the current line as an array of characters
char[] checkline = betaFileLine.ToCharArray();

// Iterate for each character add to you file?
foreach (char cl in checkline)

答案 1 :(得分:0)

System.String实现IEnumerable - 您需要使用代码

foreach (char cl in checkLine)
{
    ...
    File.AppendAllText(fileName, cl.ToString());
}

我还建议您将其全部放入内存中的流或StringBuilder并将其全部保存到文件中,而不是分别将每个字符写入FileStream。

答案 2 :(得分:0)

我会使用正则表达式将输入字符串拆分为所需字符数量的块。这是一个例子:

string input = File.ReadAllText(inputFilePath);
MatchCollection lines = Regex.Matches(input, ".{1200}", RegexOptions.Singleline); // matches any character including \n exactly 1200 times
StringBuilder output = new StringBuilder();

foreach (Match line in lines)
{
    output.AppendLine(line.Value);
}

File.AppendAllText(outputFilePath, output.ToString());