【问题标题】:How to read and sort a text file如何读取和排序文本文件
【发布时间】:2019-03-28 04:37:37
【问题描述】:

如何阅读和排序文本文件

对不起,如果这是一个简单的问题,我是编码新手。我尝试了许多在线解决方案,但似乎没有一个能解决我的问题:

namespace Login_but_it_hopefully_works
{
    public partial class Leaderboard : Form
    {
        string Line = "";
        private string filepath1 = @"Compdetails.txt";
        FileStream readerStream = new FileStream("Compdetails.txt", FileMode.Open);
        string[] content = null;
        public Leaderboard()
        {
            InitializeComponent();
        }

        public object ListReadFile { get; private set; }

        private void bttn_load_Click(object sender, EventArgs e)
        {
            string[] content = null;
            //Read the content
            using (StreamReader CompTXT = File.OpenText(filepath1))
            {
                content = CompTXT.ReadToEnd().Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);

                //Remove the entries in the file
                readerStream.SetLength(0);
            }

            FileStream writerStream = new FileStream(@"Desktop\Source\text.txt", FileMode.OpenOrCreate);
            using (StreamWriter writer = new StreamWriter(writerStream))
            {
                //Sort the content and write back to the same file
                Array.Sort(content);
                writer.Write(string.Join(Environment.NewLine, content));
            }
        }
    }
}

错误是:

附加信息:进程无法访问文件 'E:\CS\Login\Login 但它希望可以工作\bin\Debug\Compdetails.txt' 因为它正在被另一个进程使用并且该行是“ using (StreamReader CompTXT = File.OpenText(filepath3))"

【问题讨论】:

  • 您能确认您实际上没有在其他编辑器中打开该文件吗?错误行引用了一个文件路径 3。你的意思是它是filepath1吗?此外,您发布的错误消息中还有一些您可能想要删除的额外字词。
  • 您能解释一下 text.txt 和 Compdetails.txt 的用途以及您想对这两个文件做什么吗?
  • var lines = File.ReadAllLines("yourTextFile"); File.WriteAllLines("someTextFile", lines.OrderBy(x => x));

标签: c#


【解决方案1】:

删除涉及readerStream 的两行。他们没有完成你认为的那样,但他们正在导致错误。 :-) 您的下一个任务将是覆盖文件而不是附加到它。

详细说明错误的原因:在类中声明该字段并通​​过打开流进行初始化会导致文件被锁定,只要该类的实例存在。当您随后调用按钮事件方法并尝试在同一文件上打开另一个具有另一个锁的流时,会导致异常。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-01-05
    • 2017-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-01-04
    相关资源
    最近更新 更多