我正在尝试删除已打开和使用的文本文件中的最后一个逗号。
我正在使用 (String.LastIndexOf
) 函数来尝试完成这项工作。
但是它不起作用。如何删除打开的文本文件中的最后一个逗号?
这是我到目前为止尝试过的:
DialogResult openFile = openFileDialog1.ShowDialog();
if (openFile == DialogResult.OK)
{
Functions func = new Functions();
string file = openFileDialog1.FileName;
string content = File.ReadAllText(file);
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "New Text Doucment";
sfd.Title = "Save As Text File";
if (sfd.ShowDialog() == DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter bw = new StreamWriter(File.Create(path));
bw.WriteLine(content);
bw.Close();
File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));
string newContent = File.ReadAllText(path);
newContent = newContent.Remove(newContent.LastIndexOf(","));
}
}
但是,当我检查文件以查看最后一个逗号被删除时,它不起作用? 我是做错了什么还是遗漏了什么?
感谢帮助!
注意:我正在获取原始文本文件,阅读其内容并在每行末尾添加一个逗号。然后我将它写在新的文本文件中,但我需要去掉最后一个逗号,因为它在 SQL(文件)中运行时会导致问题
最佳答案
不需要,改一下就可以了
File.WriteAllLines(path, File.ReadAllLines(path).Select(x => string.Format("{0},", x)));
到
File.WriteAllText(path, string.Join("," + Environment.NewLine, File.ReadAllLines(path)));
并删除另外两行。
注意:+ Environment.NewLine
在写回文件时保持行分隔,并按照注释中的建议添加。
关于c# - 如何从文本文件中删除逗号的最后一个索引?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44023783/