【发布时间】: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