0
File f = new File(filePath);

    RandomAccessFile rf=null;
    String firstLine="";
    if (f.isFile() && f.length() > 0) {
        rf = new RandomAccessFile(f, "r");

            rf.seek(0);
        firstLine = rf.readLine();
        rf.close();

上面的代码用于从 java 构造函数中的文件读取。同一个文件可以同时被不同的线程打开。现在我正在用 C# 编写代码,并且像 java 中的 File 类不存在。我想问一下 File 类的构造函数在这里是做什么的,它与我们简单地使用下面的方法有什么不同。

StreamReader sr = File.OpenText(path)

当只有从文件中读取的行是第一行时,为什么实际使用随机访问文件。由于有不同的线程,当一个线程同时在文件中读取或写入时,其他线程也可能正在读取文件。我们如何在 C# 中允许它

4

1 回答 1

0

我认为这可以解决问题:

System.IO.StreamReader file = new System.IO.StreamReader("c:\\test.txt");
string firstLine = file.ReadLine();
file.Close();
于 2012-09-04T17:41:19.553 回答