Search and Update Record in JSON file

Jassim Al Rahma 1,566 Reputation points
2022-09-19T19:00:05.487+00:00

Hi,

I have the below json file. I wanted to know using C# how can I open the file, search for the FilePath that is equal to:

/Users/jassim/Projects/MauiPad/SampleText/2.txt

Then Update the LastModified to current date?

[  
   {  
      "Id":"a2622858-1ea8-47f1-bb0e-e34906233cd6",  
      "FileName":"1",  
      "FilePath":"/Users/jassim/Projects/MauiPad/SampleText/1.txt",  
      "LastModified":"2022-09-19 22:53:54"  
   }  
   {  
      "Id":"a2622858-1ea8-47f1-bb0e-e34906233cd6",  
      "FileName":"2",  
      "FilePath":"/Users/jassim/Projects/MauiPad/SampleText/2.txt",  
      "LastModified":"2022-09-19 22:53:54"  
   }  
   {  
      "Id":"a2622858-1ea8-47f1-bb0e-e34906233cd6",  
      "FileName":"3",  
      "FilePath":"/Users/jassim/Projects/MauiPad/SampleText/2.txt",  
      "LastModified":"2022-09-19 22:53:54"  
   }  
]  

Thanks,
Jassim

C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,853 questions
{count} votes

1 answer

Sort by: Most helpful
  1. AgaveJoe 28,051 Reputation points
    2022-09-19T19:12:14.07+00:00

    Please make an effort to write this code on your own first.

    Read the file and deserialize the contents into a C# type.

    How to serialize and deserialize (marshal and unmarshal) JSON in .NET
    https://learn.microsoft.com/en-us/answers/questions/699941/read-and-process-json-file-with-c.html

    Use LINQ to find the item with the file path you're looking for.

    var item = items.FirstOrDefault(i => i.FilePath == "/Users/jassim/Projects/MauiPad/SampleText/2.txt");  
    

    Make the update.

    item.LastModified = DateTime.Now;  
    

    Sterilize the items back into a file.

    1 person found this answer helpful.
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.