【问题标题】:Read file, check correctness of column, write file C#读取文件,检查列的正确性,写入文件 C#
【发布时间】:2015-05-27 16:16:57
【问题描述】:

我需要检查某些数据列以确保没有尾随空格。起初我以为这很容易,但在尝试实现目标之后我就卡住了。

我知道我需要检查的列中应该有 6 位数字。如果少我会拒绝,如果有更多我会修剪空格。对整个文件执行此操作后,我想将其写回具有相同分隔符的文件。

这是我的尝试:

除了写入文件外,一切似乎都正常工作。

if (File.Exists(filename))
            {
                using (StreamReader sr = new StreamReader(filename))
                {
                    string lines = sr.ReadLine();
                    string[] delimit = lines.Split('|');

                    while (delimit[count] != "COLUMN_DATA_TO_CHANGE")
                    {
                        count++;
                    }

                    string[] allLines = File.ReadAllLines(@filename);

                    foreach(string nextLine in allLines.Skip(1)){
                        string[] tempLine = nextLine.Split('|');
                        if (tempLine[count].Length == 6)
                        {
                            checkColumn(tempLine);
                            writeFile(tempLine);
                        }
                        else if (tempLine[count].Length > 6)
                        {
                            tempLine[count] = tempLine[count].Trim();
                            checkColumn(tempLine);                               
                        }
                        else
                        {
                            throw new Exception("Not enough numbers");
                        }
                    }
                }
            }
        } 

 public static void checkColumn(string[] str)
    {
        for (int i = 0; i < str[count].Length; i++)
        {
            char[] c = str[count].ToCharArray();
            if (!Char.IsDigit(c[i]))
            {
                throw new Exception("A non-digit is contained in data");
            }
        }
    }

    public static void writeFile(string[] str)
    {
        string temp;
        using (StreamWriter sw = new StreamWriter(filename+ "_tmp", false))
        {
            StringBuilder builder = new StringBuilder();
            bool firstColumn = true;

            foreach (string value in str)
            {
                if (!firstColumn)
                {
                    builder.Append('|');
                }
                if (value.IndexOfAny(new char[] { '"', ',' }) != -1)
                {
                    builder.AppendFormat("\"{0}\"", value.Replace("\"", "\"\""));
                }
                else
                {
                    builder.Append(value);
                }
                firstColumn = false;
            }
            temp = builder.ToString();
            sw.WriteLine(temp);
        }
    }

如果有更好的方法来解决这个问题,我很想听听。感谢您查看问题。

编辑: 文件结构-

国家|名字|姓氏| uniqueID(我正在检查的列)|地址|等等

美国|约翰|Doe|123456 |5 大街|

注意6后面的空格

【问题讨论】:

  • 你可以创建一个模仿文件结构的类。然后你可以在一个函数调用中读取所有文本。然后你可以从那里创建一个 List 并保存数据这样,一旦完成,您可以将所有数据以分隔格式保存到同一个文件中。您还可以展示文件结构的单行示例
  • @MethodMan 对问题添加了编辑
  • 您的文件有多长?理想情况下,如果您可以在创建文件时控制 id 上的 .trim() ,那将是最佳解决方案。否则读取整个文件,修剪,然后将其写回将是第二个最简单的方法。
  • 文件长度可能因上传文件的人而异。我的测试文件有 66 行长,但其他的可能有几千行
  • @AlexanderMatusiak 不幸的是,在创建文件时,我将无法访问它们。它们被上传到我们的服务器供我们处理。

标签: c# visual-studio file-io delimiter


【解决方案1】:
var oldLines = File.ReadAllLines(filePath):
var newLines = oldLines.Select(FixLine).ToArray();
File.WriteAllLines(filePath, newLines);

string FixLine(string oldLine)
{
    string fixedLine = ....
    return fixedLine;
}

【讨论】:

    【解决方案2】:

    写入文件的主要问题是您打开每个输出行的输出文件,并且使用 append=false 打开它,这会导致文件每次都被覆盖。更好的方法是打开输出文件一次(可能在验证输入文件头之后)。

    另一个问题是您使用 .ReadAllLines() 再次打开输入文件。最好在循环中一次一行地读取现有文件。

    考虑这个修改:

    using (StreamWriter sw = new StreamWriter(filename+ "_tmp", false))
    {
        string nextLine;
    
        while ((nextLine = sr.ReadLine()) != null)
        {
            string[] tempLine = nextLine.Split('|');
            ...
            writeFile(sw, tempLine);
    

    【讨论】:

      猜你喜欢
      • 2013-03-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-09-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多