读取文件,检查列的正确性,写入文件C#

读取文件,检查列的正确性,写入文件C#,c#,visual-studio,file-io,delimiter,C#,Visual Studio,File Io,Delimiter,我需要检查某些列的数据,以确保没有尾随空格。起初我以为这很容易,但在试图实现目标后,我陷入了困境 我知道我需要检查的列中应该有6位数字。如果少了我会拒绝,如果有更多的话我会修剪空白。对整个文件执行此操作后,我希望使用相同的分隔符将其写回文件 这是我的尝试: 除了写文件外,一切似乎都正常工作 if (File.Exists(filename)) { using (StreamReader sr = new StreamReader(filen

我需要检查某些列的数据,以确保没有尾随空格。起初我以为这很容易,但在试图实现目标后,我陷入了困境

我知道我需要检查的列中应该有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);
        }
    }
if(File.Exists(filename))
{
使用(StreamReader sr=新StreamReader(文件名))
{
字符串行=sr.ReadLine();
字符串[]定界=行。拆分(“|”);
while(定界[计数]!=“列数据更改”)
{
计数++;
}
string[]allLines=File.ReadAllLines(@filename);
foreach(所有行中的下一行字符串。跳过(1)){
string[]tempLine=nextLine.Split(“|”);
if(模板行[count].Length==6)
{
检查列(模板行);
写入文件(模板行);
}
else if(模板行[count]。长度>6)
{
模板行[count]=模板行[count].Trim();
检查列(模板行);
}
其他的
{
抛出新异常(“数量不足”);
}
}
}
}
} 
公共静态无效检查列(字符串[]str)
{
对于(int i=0;i
如果有更好的方法,我很乐意听到。谢谢你看这个问题

编辑: 文件结构-

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

美国|约翰|多伊| 123456 | 5大街|


注意6

后的空白:编写文件的主要问题是,为每个输出行打开输出文件,然后用AppOnt= false打开它,这会使文件每次都被重写。更好的方法是一次性打开输出文件(可能在验证输入文件头之后)

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

考虑这一修改:

using (StreamWriter sw = new StreamWriter(filename+ "_tmp", false))
{
    string nextLine;

    while ((nextLine = sr.ReadLine()) != null)
    {
        string[] tempLine = nextLine.Split('|');
        ...
        writeFile(sw, tempLine);

您可以创建一个模仿文件结构的类。。然后,您可以在单个函数调用中读取所有文本。。然后,您可以从那里创建一个列表并以这种方式保存数据,完成后,您可以将所有数据以分隔格式保存回同一文件。。您还可以展示文件结构外观的单行示例吗like@MethodMan在问题中添加了编辑您的文件有多长?理想情况下,如果您可以在创建文件时控制id上的.trim(),这将是最好的解决方案。否则,读入、修剪整个文件,然后将其写回将是第二种最简单的方法。文件长度可能因上传文件的人而异。我的测试文件有66行长,但其他的可能有好几行thousand@AlexanderMatusiak很遗憾,在创建文件时,我将无法访问这些文件。它们被上传到我们的服务器上,供我们处理。
var oldLines = File.ReadAllLines(filePath):
var newLines = oldLines.Select(FixLine).ToArray();
File.WriteAllLines(filePath, newLines);

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