C#更改文件中的特定行

C#更改文件中的特定行,c#,file-handling,C#,File Handling,我有一个文本文件,其中包含一些我想编辑的信息。该文件如下所示: id: 31 name: Anna profession: Doctor id: 31 name: Anna 我可以使用StreamReader读取该条目,并将其显示在我的应用程序中。然后,我希望用户能够更改条目的name和profession,因此我希望将这些特定行编辑为新值,同时保持id的完整性(在我的真实代码中,不是只有几行,而是很多行,其中只有一些行需要更改)。例如,在我的操作结束时,我希望文件看起来像这样 id: 31

我有一个文本文件,其中包含一些我想编辑的信息。该文件如下所示:

id: 31
name: Anna
profession: Doctor
id: 31
name: Anna
我可以使用
StreamReader
读取该条目,并将其显示在我的应用程序中。然后,我希望用户能够更改条目的
name
profession
,因此我希望将这些特定行编辑为新值,同时保持
id
的完整性(在我的真实代码中,不是只有几行,而是很多行,其中只有一些行需要更改)。例如,在我的操作结束时,我希望文件看起来像这样

id: 31
name: Emma
profession: Programmer
但是,我还必须考虑到,有时行事先并不存在。例如,在将安娜编辑到艾玛之前,不确定她是否有职业,文件可能是这样的:

id: 31
name: Anna
profession: Doctor
id: 31
name: Anna
在这种情况下,我想在最后添加一行
profession:Programmer

我尝试使用带有
ReadWrite
访问权限的
FileStream
,我给了
StreamReader
StreamWriter
,但后来我发现没有办法更改或替换一行文本,只能在保留旧文本的同时读取和写入一行相同的新文本

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.writeAllines
访问该文件,因为
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
var-previousData=File.ReadAllLines(filePath);
var newData=newlist();
bool-idExists=false;
bool nameExists=false;
bool professionExists=false;
for(int i=0;i

如果您已经在条目中向用户提供了数据,使用户可以编辑
名称
专业
,您只需读取文件,获取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; }
}

现在,如果您有权限问题,您只需了解如何访问该文件。

如果您已经在条目中向用户提供了数据,使用户可以编辑
名称
专业
,您只需读取该文件,获取ID,并用条目的值填充文件的其余部分。T下面是一个控制台应用程序示例

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; }
}

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

我现在才了解自己无法执行文件的原因。WriteAllines不是因为文件忙,访问被拒绝,因为我不知道如何解决。我将编辑我的问题。如果您觉得我的解决方案有帮助,我会帮助您如果您将其标记为答案,我将不胜感激:)哦,对了,对不起,我忘了!可以。我现在才发现我不能做File.writeAllines的原因不是因为文件忙,访问被拒绝,因为我不知道如何解决。我会编辑我的问题。如果你觉得我的解决方案有帮助,我将非常感谢你将其标记为答案:)哦,对,对不起,我忘了!可以。从一个文件中读取、删除并写入一个新文件确实是最简单的方法!从一个文件中读取、删除并写入一个新文件确实是最简单的方法!