c save string to file

These examples show various ways to write text to a file. The first two examples use static convenience methods on the System.IO.File class to write each element of any IEnumerable and a string to a text file. Example 3 shows how to add text to a file when you have to process each line individually as you write to the file. Examples 1-3 overwrite all existing content in the file, but example 4 shows you how to append text to an existing file.

These examples all write string literals to files. If you want to format text written to a file, use the Format method or C# string interpolation feature.

Example

Robust Programming

The following conditions may cause an exception:

This is a C program to write to text file.

The user is prompted to enter the name of the file to write to and also the string that has to be written. If the specified file already exists then it will be overwritten. The filename is passed as the first parameter to the fopen() function. The second parameter of fopen() function is w+ which means to open the file for reading and writing.

The fopen() function return a pointer to the FILE stream which is then used with the fputs() function to write the string to the file.

I have a string with a C# program that I want to write to a file and always overwrite the existing content. If the file isn’t there, the program should create a new file instead of throwing an exception.

4 Answers 4

  • If the file exists, this overwrites it.
  • If the file does not exist, this creates it.
  • Please make sure you have appropriate privileges to write at the location, otherwise you will get an exception.

Use the File.WriteAllText method. It creates the file if it doesn’t exist and overwrites it if it exists.

Generally, FileMode.Create is what you’re looking for.

If your code doesn’t require the file to be truncated first, you can use the FileMode.OpenOrCreate to open the filestream, which will create the file if it doesn’t exist or open it if it does. You can use the stream to point at the front and start overwriting the existing file?

I’m assuming your using a streams here, there are other ways to write a file.

Not the answer you’re looking for? Browse other questions tagged c# file text or ask your own question.

Linked

Hot Network Questions

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2019 Stack Exchange Inc; user contributions licensed under cc by-sa 4.0 with attribution required. rev 2019.11.15.35459

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