Csharp string to file

Csharp string to file

Для работы непосредственно с текстовыми файлами в пространстве System.IO определены специальные классы: StreamReader и StreamWriter .

Запись в файл и StreamWriter

Для записи в текстовый файл используется класс StreamWriter . Некоторые из его конструкторов, которые могут применяться для создания объекта StreamWriter:

  • StreamWriter(string path) : через параметр path передается путь к файлу, который будет связан с потоком
  • StreamWriter(string path, bool append) : параметр append указывает, надо ли добавлять в конец файла данные или же перезаписывать файл. Если равно true, то новые данные добавляются в конец файла. Если равно false, то файл перезаписываетсяя заново
  • StreamWriter(string path, bool append, System.Text.Encoding encoding) : параметр encoding указывает на кодировку, которая будет применяться при записи

Свою функциональность StreamWriter реализует через следующие методы:

  • int Close() : закрывает записываемый файл и освобождает все ресурсы
  • void Flush() : записывает в файл оставшиеся в буфере данные и очищает буфер.
  • Task FlushAsync() : асинхронная версия метода Flush
  • void Write(string value) : записывает в файл данные простейших типов, как int, double, char, string и т.д. Соответственно имеет ряд перегруженных версий для записи данных элементарных типов, например, Write(char value) , Write(int value) , Write(double value) и т.д.
  • Task WriteAsync(string value) : асинхронная версия метода Write. Обратите внимание, что асинхронные версии есть не для всех перегрузок метода Write.
  • void WriteLine(string value) : также записывает данные, только после записи добавляет в файл символ окончания строки
  • Task WriteLineAsync(string value) : асинхронная версия метода WriteLine
Читайте также:  Java object is subclass

Рассмотрим запись в файл на примере:

string path = «note1.txt»; string text = «Hello World\nHello METANIT.COM»; // полная перезапись файла using (StreamWriter writer = new StreamWriter(path, false)) < await writer.WriteLineAsync(text); >// добавление в файл using (StreamWriter writer = new StreamWriter(path, true))

В данном случае два раза создаем объект StreamWriter. В первом случае если файл существует, то он будет перезаписан. Если не существует, он будет создан. И в нее будет записан текст из переменной text. Во втором случае файл открывается для дозаписи, и будут записаны атомарные данные — строка и число.

По завершении в папке программы мы сможем найти файл note.txt, который будет иметь следующие строки:

Hello World Hello METANIT.COM Addition 4,5

В пример выше будет использоваться кодировка по умолчанию. но также можно задать ее явным образом:

using (StreamWriter writer = new StreamWriter(path, true, System.Text.Encoding.Default)) < // операции с writer >

Чтение из файла и StreamReader

Класс StreamReader позволяет нам легко считывать весь текст или отдельные строки из текстового файла.

Некоторые из конструкторов класса StreamReader:

  • StreamReader(string path) : через параметр path передается путь к считываемому файлу
  • StreamReader(string path, System.Text.Encoding encoding) : параметр encoding задает кодировку для чтения файла

Среди методов StreamReader можно выделить следующие:

  • void Close() : закрывает считываемый файл и освобождает все ресурсы
  • int Peek() : возвращает следующий доступный символ, если символов больше нет, то возвращает -1
  • int Read() : считывает и возвращает следующий символ в численном представлении. Имеет перегруженную версию: Read(char[] array, int index, int count) , где array — массив, куда считываются символы, index — индекс в массиве array, начиная с которого записываются считываемые символы, и count — максимальное количество считываемых символов
  • Task ReadAsync() : асинхронная версия метода Read
  • string ReadLine() : считывает одну строку в файле
  • string ReadLineAsync() : асинхронная версия метода ReadLine
  • string ReadToEnd() : считывает весь текст из файла
  • string ReadToEndAsync() : асинхронная версия метода ReadToEnd

Сначала считаем текст полностью из ранее записанного файла:

string path = «note1.txt»; // асинхронное чтение using (StreamReader reader = new StreamReader(path))

Считаем текст из файла построчно:

string path = "/Users/eugene/Documents/app/note1.txt"; // асинхронное чтение using (StreamReader reader = new StreamReader(path)) < string? line; while ((line = await reader.ReadLineAsync()) != null) < Console.WriteLine(line); >>

В данном случае считываем построчно через цикл while: while ((line = await reader.ReadLineAsync()) != null) — сначала присваиваем переменной line результат функции reader.ReadLineAsync() , а затем проверяем, не равна ли она null. Когда объект sr дойдет до конца файла и больше строк не останется, то метод reader.ReadLineAsync() будет возвращать null.

Источник

How to: Write text to a file

This article shows different ways to write text to a file for a .NET app.

The following classes and methods are typically used to write text to a file:

  • StreamWriter contains methods to write to a file synchronously (Write and WriteLine) or asynchronously (WriteAsync and WriteLineAsync).
  • File provides static methods to write text to a file such as WriteAllLines and WriteAllText, or to append text to a file such as AppendAllLines, AppendAllText, and AppendText.
  • Path is for strings that have file or directory path information. It contains the Combine method and in .NET Core 2.1 and later, the Join and TryJoin methods. These methods let you concatenate strings for building a file or directory path.

The following examples show only the minimum amount of code needed. A real-world app usually provides more robust error checking and exception handling.

Example: Synchronously write text with StreamWriter

The following example shows how to use the StreamWriter class to synchronously write text to a new file one line at a time. Because the StreamWriter object is declared and instantiated in a using statement, the Dispose method is invoked, which automatically flushes and closes the stream.

using System; using System.IO; class Program < static void Main(string[] args) < // Create a string array with the lines of text string[] lines = < "First line", "Second line", "Third line" >; // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the string array to a new file named "WriteLines.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"))) < foreach (string line in lines) outputFile.WriteLine(line); >> > // The example creates a file named "WriteLines.txt" with the following contents: // First line // Second line // Third line 
Imports System.IO Class WriteText Public Shared Sub Main() ' Create a string array with the lines of text Dim lines() As String = ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the string array to a new file named "WriteLines.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt"))) For Each line As String In lines outputFile.WriteLine(line) Next End Using End Sub End Class ' The example creates a file named "WriteLines.txt" with the following contents: ' First line ' Second line ' Third line 

Example: Synchronously append text with StreamWriter

The following example shows how to use the StreamWriter class to synchronously append text to the text file created in the first example:

using System; using System.IO; class Program < static void Main(string[] args) < // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Append text to an existing file named "WriteLines.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteLines.txt"), true)) < outputFile.WriteLine("Fourth Line"); >> > // The example adds the following line to the contents of "WriteLines.txt": // Fourth Line 
Imports System.IO Class AppendText Public Shared Sub Main() ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Append text to an existing file named "WriteLines.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteLines.txt")), True) outputFile.WriteLine("Fourth Line") End Using End Sub End Class ' The example adds the following line to the contents of "WriteLines.txt": ' Fourth Line 

Example: Asynchronously write text with StreamWriter

The following example shows how to asynchronously write text to a new file using the StreamWriter class. To invoke the WriteAsync method, the method call must be within an async method.

using System; using System.IO; using System.Threading.Tasks; class Program < static async Task Main() < // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the specified text asynchronously to a new file named "WriteTextAsync.txt". using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, "WriteTextAsync.txt"))) < await outputFile.WriteAsync("This is a sentence."); >> > // The example creates a file named "WriteTextAsync.txt" with the following contents: // This is a sentence. 
Imports System.IO Public Module Example Public Sub Main() WriteTextAsync() End Sub Async Sub WriteTextAsync() ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the text asynchronously to a new file named "WriteTextAsync.txt". Using outputFile As New StreamWriter(Path.Combine(docPath, Convert.ToString("WriteTextAsync.txt"))) Await outputFile.WriteAsync("This is a sentence.") End Using End Sub End Module ' The example creates a file named "WriteTextAsync.txt" with the following contents: ' This is a sentence. 

Example: Write and append text with the File class

The following example shows how to write text to a new file and append new lines of text to the same file using the File class. The WriteAllText and AppendAllLines methods open and close the file automatically. If the path you provide to the WriteAllText method already exists, the file is overwritten.

using System; using System.IO; class Program < static void Main(string[] args) < // Create a string with a line of text. string text = "First line" + Environment.NewLine; // Set a variable to the Documents path. string docPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); // Write the text to a new file named "WriteFile.txt". File.WriteAllText(Path.Combine(docPath, "WriteFile.txt"), text); // Create a string array with the additional lines of text string[] lines = < "New line 1", "New line 2" >; // Append new lines of text to the file File.AppendAllLines(Path.Combine(docPath, "WriteFile.txt"), lines); > > // The example creates a file named "WriteFile.txt" with the contents: // First line // And then appends the following contents: // New line 1 // New line 2 
Imports System.IO Class WriteFile Public Shared Sub Main() ' Create a string array with the lines of text Dim text As String = "First line" & Environment.NewLine ' Set a variable to the Documents path. Dim docPath As String = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) ' Write the text to a new file named "WriteFile.txt". File.WriteAllText(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), text) ' Create a string array with the additional lines of text Dim lines() As String = ' Append new lines of text to the file File.AppendAllLines(Path.Combine(docPath, Convert.ToString("WriteFile.txt")), lines) End Sub End Class ' The example creates a file named "WriteFile.txt" with the following contents: ' First line ' And then appends the following contents: ' New line 1 ' New line 2 

See also

Feedback

Submit and view feedback for

Источник

Csharp save string to file c code example

How to write to a text file, Write one string to a file. C#. Copy. class WriteAllText < public static async Task ExampleAsync() < string text = "A class is the most powerful data type in C#. Like a structure, " + "a class defines the data and behavior of the data type. "; await File.WriteAllTextAsync ("WriteText.txt", text); >> The preceding source … Code sampleSystem.IO.File.WriteAllText(@»C:\Users\Public\TestFolder\WriteText.txt», text);using (System.IO.StreamWriter file =new System.IO.StreamWriter(@»C:\Users\Public\TestFolder\WriteLines2.txt»))

Save object to file C#

Save object to file C#

/// /// Serializes an object. /// /// /// /// public void SerializeObject(T serializableObject, string fileName) < if (serializableObject == null) < return; >try < XmlDocument xmlDocument = new XmlDocument(); XmlSerializer serializer = new XmlSerializer(serializableObject.GetType()); using (MemoryStream stream = new MemoryStream()) < serializer.Serialize(stream, serializableObject); stream.Position = 0; xmlDocument.Load(stream); xmlDocument.Save(fileName); >> catch (Exception ex) < //Log exception here >> /// /// Deserializes an xml file into an object list /// /// /// /// public T DeSerializeObject(string fileName) < if (string.IsNullOrEmpty(fileName)) < return default(T); >T objectOut = default(T); try < XmlDocument xmlDocument = new XmlDocument(); xmlDocument.Load(fileName); string xmlString = xmlDocument.OuterXml; using (StringReader read = new StringReader(xmlString)) < Type outType = typeof(T); XmlSerializer serializer = new XmlSerializer(outType); using (XmlReader reader = new XmlTextReader(read)) < objectOut = (T)serializer.Deserialize(reader); >> > catch (Exception ex) < //Log exception here >return objectOut; >

Saving data to a file in C#, Example. // To save the characterSheet variable contents to a file. WriteToBinaryFile («C:\CharacterSheet.pfcsheet», characterSheet); // To load the file contents back into a variable. CharacterSheet characterSheet = ReadFromBinaryFile

C# save file to folder

using (var fileStream = File.Create(«C:\\Path\\To\\File»))

Источник

Оцените статью