【发布时间】: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#