How to read/write files in .Net Core?
Asked Answered
D

7

83

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.

Daimyo answered 17/1, 2017 at 15:24 Comment(0)
P
102

Package: System.IO.FileSystem

System.IO.File.ReadAllText("MyTextFile.txt"); ?
Perlman answered 17/1, 2017 at 15:45 Comment(0)
L
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.

Lacreshalacrimal answered 17/1, 2017 at 15:33 Comment(3)
be advised, there seems to be no FileStream.Lock / .UnlockGrossman
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: cc.davelozinski.com/c-sharp/…Rainier
@ChrisHansen That's about async processing of the data, not the reading...Lacreshalacrimal
S
9

Works in Net Core 2.1

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

    string SendData = System.IO.File.ReadAllText(file);
Showily answered 19/9, 2019 at 6:30 Comment(0)
L
8

To write:

using (System.IO.StreamWriter file =
new System.IO.StreamWriter(System.IO.File.Create(filePath).Dispose()))
{
    file.WriteLine("your text here");
}
Lax answered 27/6, 2017 at 8:59 Comment(5)
Possible memory leak on System.IO.File.Create(filePath)Ani
Could you give me a link or some reasons @ManIkWeet? This is the standard tutorial from MS.Lax
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.Ani
Well, I see, it should be System.IO.File.Create(filePath).Dispose() . Do you agree?Lax
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"); }Ani
S
5

Use:

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

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

Sweetheart answered 2/6, 2017 at 10:0 Comment(1)
this is a dot net core question not a dot net framework reference .Practise
C
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.

Cambogia answered 8/5, 2019 at 8:42 Comment(0)
P
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.

Pheasant answered 9/11, 2018 at 6:5 Comment(1)
remove the break;Pheasant

© 2022 - 2024 — McMap. All rights reserved.