我删除了上一篇文章,希望这篇文章更好、更清晰,以便能够获得帮助。我很感激。
到目前为止,通过我的代码,我正在上传一个 CSV 文件,将其格式化为:我跳过了标题,并且添加了管道分隔符 | 而不是逗号分隔符。并在创建新的 CSV 文件时删除所有行中的以下值:“.\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001”。
我无法解决的问题是上传新的 CSV 文件时,我需要删除的值: ".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001" 。最后一个数字:_0001" 在我上传到格式化的每个 CSV 文件上都会递增 1。
我需要有关如何删除整个字符串值(包括最后一个值的增量)的帮助:
".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001" 。最后一个数字:_0001"
".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001" 。最后一个数字:_0002”
".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001" 。最后一个数字:_0003”
".\MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001" 。最后一个数字:_0004"
这是我的代码:
谢谢你
private void button2_Click(object sender, EventArgs e)
{
try
{
if (String.IsNullOrEmpty(FromFile))
{
lblStatus.Text = "Missing CSV Information";
Application.DoEvents();
MessageBox.Show("Please select CSV file first.");
return;
}
if (String.IsNullOrEmpty(ToFile))
{
lblStatus.Text = "Missing Save Information";
Application.DoEvents();
MessageBox.Show("Please enter save information.");
return;
}
else if (File.Exists(ToFile))
{
// delete old file
File.Delete(ToFile);
}
btnProcess.Enabled = false;
lblStatus.Text = "Processing...";
Application.DoEvents();
var lines = File.ReadAllLines(FromFile).Skip(1);
string docId = "";
string[] oldLine = null;
foreach (var line in lines)
{
var newLine = line.Replace("\"", "").Replace(".\\", "").Replace("\\", "").Replace("MEMBERRECORDS_SIGNATURECARD_00000000_00000000_0001", "").Split(',');
if (docId != newLine[0])
{
docId = newLine[0];
oldLine = newLine;
}
else
{
for (int i = COPY_FROM - 1; i < newLine.Length; i++)
newLine[i] = oldLine[i];
}
using (StreamWriter sr = new StreamWriter(ToFile, true))
{
sr.WriteLine(string.Join("|", newLine));
}
}
btnProcess.Enabled = true;
lblStatus.Text = "Completed";
Application.DoEvents();
}
catch (Exception ex)
{
MessageBox.Show("Error! Ex: " + ex.Message);
}
}`
在这种情况下,我会使用正则表达式,因为它应该匹配多个数字组合。
类似:
// Regex pattern
string pattern = @"\.\MEMBERRECORDS_SIGNATURECARD_\d{8}_\d{8}_\d{4}";
// Create a compiled regex object
Regex regex = new Regex(pattern, RegexOptions.Compiled);
// for each line...
foreach(var line in file)
{
// first remove the slashes.
var removedSlashes = line.Replace("\"", "").Replace(".\\", "").Replace("\\", "");
// call the regex.Replace and it should replace a match with empty string.
var newLine = regex.Replace(removedSlashes, "").Split(',');
// rest of code...
}