如何阅读和排序文本文件

时间:2019-03-27 16:16:26

标签: c#

我如何阅读和排序文本文件

很抱歉,如果这是一个简单的问题,我是编码新手。我尝试了许多在线解决方案,但似乎都无法解决我的问题:

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))“

1 个答案:

答案 0 :(得分:1)

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

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

相关问题