读取文件,检查列的正确性,编写文件



我需要检查某些数据列,以确保没有尾随空格。一开始我以为会很容易,但在试图实现目标后,我却卡住了。

我知道在我需要检查的列中应该有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);
        }
    }

如果有更好的方法,我很乐意听到。谢谢你看这个问题。

编辑:文件结构——

国家|名|姓|唯一id(我正在检查的列)|地址|等

USA|John|Doe|123456 |5 main street|

注意6后面的空格

var oldLines = File.ReadAllLines(filePath):
var newLines = oldLines.Select(FixLine).ToArray();
File.WriteAllLines(filePath, newLines);
string FixLine(string oldLine)
{
    string fixedLine = ....
    return fixedLine;
}

编写该文件的主要问题是为每个输出行打开输出文件,并且使用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);

最新更新