locked
Update contents of text file RRS feed

  • Question

  • User-73514677 posted

    Hi.

    I have a text file, which contains data in the below format:

    [Dict], TargetFolder, C:\Data\
    [Dict], ToDate, 2020-09-13
    [Dict], FromDate, 2020-05-04
    [Dict], ErrorPath, C:\Data\Log
    

    How to update the contents of file dynamically.  Example: value of FromDate to be updated as : 2020-08-03

    How to achieve this in c# ? Thanks

    Sunday, November 8, 2020 9:16 AM

All replies

  • User475983607 posted

    Looks like a typical comma separated file.  Updating the FromDate is trivial at best.  Share your code so we can see what you are doing.  

    Sunday, November 8, 2020 11:41 AM
  • User-73514677 posted

    HI.

    Please find the below code, which i have tried:

    FileStream fsIn = new FileStream(fileName, FileMode.Open, FileAccess.Write, FileShare.Read);
    using (StreamReader sr = new StreamReader(fsIn))
     {
      string   line = sr.ReadLine();
    
         while (!String.IsNullOrEmpty(line)
         {
            line = sr.ReadLine();
    	if(line.contains("FromDate")) { 
          // update the FromDate value
         }
     }

    Sunday, November 8, 2020 12:09 PM
  • User475983607 posted

    Below is a hint.  It seems like you are not trying at all...

     while (!String.IsNullOrEmpty(line)
     {
        line = sr.ReadLine();
        string[] items = line.Split(",");
    if(itmes[1] = "FromDate") items[2] = "2020-08-03"; //write code to save the file with the new value }

    Also, it looks like the you might have a custom file format due to the [Dict].  Maybe you should be reading the lines into a Dictionary???  Perhaps there is someone on your team that can help you understand how the application works?

            static async Task Main (string[] args)
            {
                Dictionary<string, string> dic = new Dictionary<string, string>();
                using (StreamReader sr = new StreamReader(fileName))
                {
                    string line;
                    while ((line = sr.ReadLine()) != null)
                    {
                        string[] items = line.Split(",");
                        dic.Add(items[1], items[2]);
                    }
                }
                dic["FromDate"] = "2020-05-04";
    
                foreach(var item in dic)
                {
                    Console.WriteLine($"{item.Key} = {item.Value}");
                }
            }

    Sunday, November 8, 2020 12:20 PM