c# - 如何从文本文件中删除逗号的最后一个索引?

标签 c# .net winforms

我正在尝试删除已打开和使用的文本文件中的最后一个逗号。 我正在使用 (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/

相关文章:

c# - 如何强制 File.Move/File.Copy 使用特定的网络接口(interface)卡 (NIC) C#?

c# - Listview Details View 不显示任何内容

c# - 使用 .exe 合并 XML 配置文件

c# - 构建嵌套条件表达式树

c# - 指定相对路径

c# - 在 ASP.NET 网站中正确使用文件设计器文件

c# - winform 应用程序是否有可能从根目录以外的路径加载其 dll?

c# - 实现提供者模式?

c# - 为什么我必须显式调用 GC 收集?

c# - 2种以上颜色混色