Search code examples
c#file-writingfile-read

how to save and open your own file C#


When I press the save button in my program, I want to save a file with my own extension. (Example .xyz)

Then I want to open it and read the data inside it through this program.

How I can achieve this?


Solution

  • When I press the save button in my program, I want to save a file with my own extension. (Example .xyz). Do the following:

    const string directory = @"D:\Temp"; // this can be any location you want
    
    if (!Directory.Exists(directory))
        Directory.CreateDirectory(directory);
    
    string path = Path.Combine(directory, "Test.custom");
    if (!File.Exists(path))
    {
        File.Create(path);
    
        // other logic
    }
    

    Then I want to open it and read the data inside it through this program.

    string textFile = @"D:\Torrent\Test.custom";
    
    using StreamReader sr = new StreamReader(textFile);
    var line = sr.ReadToEnd();
    Console.WriteLine(line);
    

    If you want later to save something in the file, the easiest way to do is this:

    const string textFile = @"D:\Torrent\Test.custom";
    string createText = $"Some text {Environment.NewLine}";
    File.WriteAllText(textFile, createText);