82

What are the options to read/write files in .Net Core?

I am working on my first .Net Core app and looking for File.Read*/File.Write* functions (System.IO from .Net) alternatives.

Ankit
  • 2,448
  • 3
  • 20
  • 33

7 Answers7

99

Package: System.IO.FileSystem

System.IO.File.ReadAllText("MyTextFile.txt"); ?
Scott Chamberlain
  • 124,994
  • 33
  • 282
  • 431
Leszek P
  • 1,807
  • 17
  • 24
36
FileStream fileStream = new FileStream("file.txt", FileMode.Open);
using (StreamReader reader = new StreamReader(fileStream))
{
    string line = reader.ReadLine();
}

Using the System.IO.FileStream and System.IO.StreamReader. You can use System.IO.BinaryReader or System.IO.BinaryWriter as well.

Biesi
  • 800
  • 9
  • 17
  • be advised, there seems to be no FileStream.Lock / .Unlock – user3791372 Feb 13 '17 at 08:43
  • 1
    It was considerably faster to read the entire file into an array and then process the data instead of processing each line as it was read in. For more information, check this article: http://cc.davelozinski.com/c-sharp/the-fastest-way-to-read-and-process-text-files – Chris Hansen Oct 17 '17 at 18:00
  • 1
    @ChrisHansen That's about async processing of the data, not the reading... – Biesi Dec 19 '18 at 23:41
9

Works in Net Core 2.1

    var file = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot", "email", "EmailRegister.htm");

    string SendData = System.IO.File.ReadAllText(file);
AlexGarciaN
  • 91
  • 1
  • 2
8

To write:

using (System.IO.StreamWriter file =
new System.IO.StreamWriter(System.IO.File.Create(filePath).Dispose()))
{
    file.WriteLine("your text here");
}
Chien Dang
  • 115
  • 1
  • 6
  • Possible memory leak on `System.IO.File.Create(filePath)` – ManIkWeet Dec 31 '17 at 15:14
  • Could you give me a link or some reasons @ManIkWeet? This is the standard tutorial from MS. – Chien Dang Jan 04 '18 at 08:16
  • 3
    `System.IO.File.Create(filePath)` creates a `FileStream`, which implements `IDisposable`. I'm not confident that disposing the `StreamWriter` also disposes the `FileStream` that it's wrapping around. When looking at decompiled code I can see it calls `Close()` on the wrapped `Stream`, but not `Dispose()`. Of course the garbage collector will probably dispose the wrapped `Stream` on a `Finalize()` operation, but that might be an unexpected performance impact. – ManIkWeet Jan 04 '18 at 11:48
  • Well, I see, it should be `System.IO.File.Create(filePath).Dispose()` . Do you agree? – Chien Dang Jan 04 '18 at 11:56
  • 10
    I'd simply use two `using` statements like this: `using (var fileStream = System.IO.File.Create(filePath)) using (var fileWriter = new System.IO.StreamWriter(fileStream)) { fileWriter.WriteLine("your text here"); }` – ManIkWeet Jan 04 '18 at 16:19
5

Use:

File.ReadAllLines("My textfile.txt");

Reference: https://msdn.microsoft.com/pt-br/library/s2tte0y1(v=vs.110).aspx

Ricardo Pontual
  • 3,749
  • 3
  • 28
  • 43
prashanth m
  • 87
  • 1
  • 1
2

For writing any Text to a file.

public static void WriteToFile(string DirectoryPath,string FileName,string Text)
    {
        //Check Whether directory exist or not if not then create it
        if(!Directory.Exists(DirectoryPath))
        {
            Directory.CreateDirectory(DirectoryPath);
        }

        string FilePath = DirectoryPath + "\\" + FileName;
        //Check Whether file exist or not if not then create it new else append on same file
        if (!File.Exists(FilePath))
        {
            File.WriteAllText(FilePath, Text);
        }
        else
        {
            Text = $"{Environment.NewLine}{Text}";
            File.AppendAllText(FilePath, Text);
        }
    }

For reading a Text from file

public static string ReadFromFile(string DirectoryPath,string FileName)
    {
        if (Directory.Exists(DirectoryPath))
        {
            string FilePath = DirectoryPath + "\\" + FileName;
            if (File.Exists(FilePath))
            {
                return File.ReadAllText(FilePath);
            }
        }
        return "";
    }

For Reference here this is the official microsoft document link.

Faraz Ahmed
  • 1,467
  • 2
  • 18
  • 33
1
    public static void Copy(String SourceFile, String TargetFile)
    {

        FileStream fis = null;
        FileStream fos = null;

            try
            {
                Console.Write("## Try No. " + a + " : (Write from " + SourceFile + " to " + TargetFile + ")\n");

                fis = new FileStream(SourceFile, FileMode.Open, FileAccess.ReadWrite);
                fos = new FileStream(TargetFile, FileMode.Create, FileAccess.ReadWrite);

                int intbuffer = 5242880;
                byte[] b = new byte[intbuffer];

                int i;
                while ((i = fis.Read(b, 0, intbuffer)) > 0)
                {
                    fos.Write(b, 0, i);
                }

                Console.Write("Writing file : " + TargetFile + " is successful.\n");

                break;
            }
            catch (Exception e)
            {
                Console.Write("Writing file : " + TargetFile + " is unsuccessful.\n");
                Console.Write(e);
            }
            finally
            {
                if (fis != null)
                {
                    fis.Close();
                }
                if (fos != null)
                {
                    fos.Close();
                }
            }
    }

The code above will read a big file and write to a new big file. The "intbuffer" value can be set in multiple of 1024. While both source and target file are open, it reads the big file by bytes and write to the new target file by bytes. It will not go out of memory.

RotiBlata
  • 11
  • 1