C# 更改文件中的特定行

C# Change specific lines in file

我有一个包含一些我想编辑的信息的文本文件。该文件看起来像这样:

id: 31
name: Anna
profession: Doctor

我可以用 StreamReader 阅读该条目,并将其呈现在我的申请中。然后我希望用户能够更改条目的 nameprofession,因此我想将这些特定行编辑为新值,同时保持 id 不变(在我的真实代码中,不仅有几行,还有很多行,其中只有一些应该更改)。因此,例如,我希望文件在我的操作结束时看起来像这样。

id: 31
name: Emma
profession: Programmer

但是,我还必须考虑到有时这些行事先并不存在。例如,在将 Anna 编辑为 Emma 之前,不确定她是否有职业,文件可能如下所示:

id: 31
name: Anna

在这种情况下,我想在末尾添加行 profession: Programmer

我尝试使用具有 ReadWrite 访问权限的 FileStream,我将其授予 StreamReaderStreamWriter,但后来我发现无法更改或替换一行文本,仅读取它并在保留旧行的同时写入新的相同行。

using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
using (StreamReader reader = new StreamReader(fileStream))
using (StreamWriter writer = new StreamWriter(fileStream))
{
    bool idExists = false;
    bool nameExists = false;
    bool tagsExist = false;

    string line;
    while((line = reader.ReadLine()) != null)
    {
        if (line.StartsWith("id:"))
            idExists = true;
        else if (line.StartsWith("name:"))
        {
            nameExists = true;
            line = $"name: {entryToSave.Name}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
        else if (line.StartsWith("profession:"))
        {
            professionExists = true;
            line = $"profession: {entryToSave.Profession}";
            writer.WriteLine(line); // Will write an additional line and not replace
        }
    }

    if (!idExists)
        writer.WriteLine($"id: {generatedId}");
    if (!nameExists)
        writer.WriteLine($"name: {entryToSave.Name}");
    if (!professionExists)
        writer.WriteLine($"profession: {entryToSave.Profession}");
}

我也尝试过使用File.ReadAllLines,遍历行,然后将所有行写回文件,只修改要修改的行。但是,由于某些我不明白的原因,我无法通过 File.WriteAllLines 访问该文件,因为 StreamWriter 可以访问。代码:

var previousData = File.ReadAllLines(filePath);
var newData = new List<string>();
bool idExists = false;
bool nameExists = false;
bool professionExists = false;

for (int i = 0; i < previousData.Length; i++)
{
    var line = previousData[i];

    if (line.StartsWith("id:")
        idExists = true;
    else if (line.StartsWith("name:")
    {
        nameExists = true;
        line = $"name: {entryToSave.Name}";
    }
    else if (line.StartsWith("profession:"))
    {
        professionExists = true;
        line = $"profession: {entryToSave.Profession}";
    }

    newData.Add(line);
}

if (!idExists)
    newData.Add($"id: {generatedId}");
if (!nameExists)
    newData.Add($"name: {entryToSave.Name}");
if (!professionExists)
    newData.Add($"profession: {entryToSave.Profession}");

File.WriteAllLines(filePath, newData.ToArray()); // Access denied

在文件流不相互干扰的情况下,如何最轻松地实现这一目标?

如果您已经在条目中向用户呈现数据,使用户能够编辑 nameprofession,您可以只读取文件、获取 ID 并填写其余部分文件的条目值。以下是一个示例控制台应用程序。

static void Main(string[] args)
{
    var filePath = "test.txt";

    // Simulated input from user 
    // these should come from entries in the application?
    var name = "Foo"; 
    var profession = "Bar";

    var personData = new PersonData(); // class declared below

    using (FileStream fileStream = new FileStream(filePath, FileMode.Open, FileAccess.ReadWrite))
    using (StreamReader reader = new StreamReader(fileStream))
    {
        string line;
        while ((line = reader.ReadLine()) != null)
        {
            if (line.StartsWith("id:"))
                personData.ID = line;
        }
    } // Now reader and filestream is closed, file is available again.


    // You don't specify what you would like to happen if personData.ID is null, 
    // so I make an assumption the generatedId is what you'd like to use.
    if (string.IsNullOrWhiteSpace(personData.ID)
        personData.ID = $"id: {generatedId}"; 

    // Add the data from the entries
    personData.Name = $"name: {name}";
    personData.Profession = $"profession: {profession}";

    File.Delete(filePath); // remove the file

    using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite))
    using (StreamWriter writer = new StreamWriter(fileStream))
    {
        writer.WriteLine(personData.ID);
        writer.WriteLine(personData.Name);
        writer.WriteLine(personData.Profession);
    }
}
private class PersonData
{
    public string ID { get; set; }
    public string Name { get; set; }
    public string Profession { get; set; }
}

现在您只需了解在遇到权限问题时如何访问该文件。