首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在通过FileShare FileShare.None锁定文件的同时,读取、删除和写入文件?

在通过FileShare FileShare.None锁定文件的同时,读取、删除和写入文件?
EN

Stack Overflow用户
提问于 2018-03-30 22:32:16
回答 1查看 345关注 0票数 1

这可能是以前问过的,所以我提前道歉。然而,我觉得这里有足够的东西是我的问题所独有的,所以我觉得没有理由提出这个问题。

我正在尝试使用FileStream方法打开一个文件。我需要从外部读/写锁下打开这个文件,这就是我在打开它时使用FileShare.None属性的原因。打开并锁定文件后,我将文件的内容逐行读取到字符串数组中。我根据需要更新的信息更改一行,然后将行写回文件。

我遇到的问题是,所写的行是在原来读取的行之后追加的。我需要擦除文件,一旦我从其中读取,以便我写回是文件中唯一的东西。

我很困惑,因为我不想关闭FileStream,只为写重新打开它(这应该会清除文件),因为这会释放我对文件的锁。

代码语言:javascript
复制
FileStream fs = new FileStream("trains.txt", FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

string[] lines = new string[trains.Length];

//Loop through all lines in the file
for (int i = 0; i < lines.Length; i++)
{
    lines[i] = sr.ReadLine();

    /*If the ID of the train in the file matches the parameter, then
        set the line to the InfoLine of the train.*/
    if (lines[i][0].ToString() == train.ID().ToString())
    {
        lines[i] = train.GetInfoLine();
    }
}

//Write back the lines to the file
for (int i = 0; i < lines.Length; i++)
{
    sw.WriteLine(lines[i]);
}

sw.Close();
sr.Close();
fs.Close();

在上面的代码中,trains.Length只是类对象数组的长度。GetInfoLine()是一个方法,它返回要写入文件的信息字符串。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2018-03-30 22:48:19

我会这样做:

代码语言:javascript
复制
string line = "";
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None);
StreamReader sr = new StreamReader(fs);
StreamWriter sw = new StreamWriter(fs);

List<string> lines = new List<string>();

while ((line = sr.ReadLine()) != null)
{
    line = "*" + line; //Do your processing
    lines.Add(line);
}

fs.SetLength(0);

foreach (var newline in lines)
{
    sw.WriteLine(newline);
}
sw.Flush();
fs.Close();

fs.SetLength(0);

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49582262

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档