Вопрос

EDIT I am not actually using a .txt file as a preferred method to store valuable data. This question is focussed on writing to a specific part of a .txt file

I'm using a .txt file as a dummy database for testing a program, and I came across the issue of re-writing a certain bit of data.

For example, the .txt file is as such:

Ben,welcome1,1
Frank,frankpassword,1
etc...

I'm using a simple method to retrieve the user information:

public void ReadUserFile(User_Model UModel)
{
    importFile = File.ReadAllText(fileName).Split('\n');
    foreach (string line in importFile)
    {
        data = line.Split(',');
        userName = data[0];
        password = data[1];
        accessLevel = Convert.ToInt32(data[2]);

        if (userName == UModel.UserName && password == UModel.UserPassword)
        {
            UModel.AccessLevel = accessLevel;
            if (UModel.UserPassword == "welcome1")
            {
                UModel.UserPassword = "change password";
                break;
            }
            break;
        }
        else { UModel.UserPassword = "invalid"; }
        lineCount++;
    }
}

And then I started writing a method to re-write the password if it was stored as 'welcome1', but when it came to it, I wasn't sure how to do it, or if it could even be done?

eg.

UModel.UserName = "Ben";
UModel.UserPassword = "welcome1";
UModel.ConfirmPassword = "newpassword";

public void UpdateUserFile(User_Model UModel)
{
    importFile = File.ReadAllText(fileName).Split('\n');
    foreach (string line in importFile)
    {
        data = line.Split(',');
        userName = data[0]; // "Ben"
        password = data[1]; // "welcome1"

        if (data[0] == UModel.UserName && UModel.UserPassword == data[1])
        {
            // Re-write "Ben,welcome1,1" to "Ben,newpassword,1"
        }
    }
}
Это было полезно?

Решение

There are at least 2 options based on how big your text file is:

  1. If the text file is only supposed to be a few lines, use this solution:

    importFile = File.ReadAllText(fileName).Split('\n');
    StringBuilder newContents = new StringBuilder();
    
    foreach (string line in importFile)
    {
        data = line.Split(',');
        userName = data[0]; // "Ben"
        password = data[1]; // "welcome1"
    
        if (data[0] == UModel.UserName && UModel.UserPassword == data[1])
        {
            line = data[0] + "," + UModel.ConfirmPassword + "," + data[2];
    
            newContents.Append(line);
            newContents.AppendLine();
        }
    }
    
    File.WriteAllText(fileName, newContents.ToString());
    
  2. If the text file is extremely huge, then you need to make use of 2 files.

Read line by line from one file, write it to another temp file line by line, till you find the matching line at which point you will write the modified line to the new file and then continue writing all the remaining lines as-is from the first file. Finally, you need to delete the old file and rename the new one to the old one.

Другие советы

If it's a dummy testing DB and performance isn't an issue, the simplest thing to do is to just read all the lines, modify them as necessary, and then rewrite the entire file from scratch. It'll be much easier than implementing in-place edits in what is essentially a linear file format.

If you really want to edit the file in-place, read up on using a StreamWriter class to open the file as a FileStream, jump to the desired location, and write a line to it. This will probably require doing the original file reading with the accompanying StreamReader so you know the exact file position of the line to replace.

its a simple program to update password according to your username .

   static void Main(string[] args)
    {


        string[] a = File.ReadAllLines(@"C:/imp.txt");// to read all lines

        Console.WriteLine("enter a name whose password  u want to change");
        string g=Console.ReadLine();
        Console.WriteLine("enter new password");
        string j = Console.ReadLine();
        for(int i=0;i<a.Length;i++)                  
        {

            string[] h = a[i].Split(',');
            if(h[0]==g)
            {
                a[i] = h[0] + ","+j+"," + h[2];
                break;// after finding a specific name,you dont need to search more 
            }

        }

        File.WriteAllLines(@"C:/imp.txt",a);//to write all data from " a "  into file


    }
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top