copy a json file in csharp

To copy a JSON file in C#, you can make use of Stream Reader and Stream Writer classes provided by C#. Here is the example code:

main.cs
using System.IO;
using Newtonsoft.Json;

class Program 
{
    static void Main(string[] args) 
    {
        string sourceFile = @"C:\source_folder\input.json";
        string destFile = @"C:\destination_folder\output.json";

        using (StreamReader sr = new StreamReader(sourceFile)) 
        {
            using (StreamWriter sw = new StreamWriter(destFile)) 
            {
                string line;
                while ((line = sr.ReadLine()) != null) 
                {
                    sw.WriteLine(line);
                }
            }
        }
    }
}
573 chars
24 lines

In the above code, we have used StreamReader to read the input.json file and StreamWriter to write the contents of input.json file to output.json file. We have specified the sourceFile and destFile paths as string variables and used them in the StreamReader and StreamWriter constructors.

We have also used Newtonsoft.Json package in our code. This package is used to handle JSON data in C#. You can install this package from NuGet package manager.

gistlibby LogSnag