To Create a Unix style text file in C# we use the NewLine Property of
the TextWriter class to set the line termination format to UNIX type.
For More information of different types of line Termination refer to
my earlier post –
Syntax of NewLine property
of TextWriter
public virtual
string NewLine { get;
set; }
If we need to create a file with Windows type of line termination, we set the NewLine property to "\r\n".
If we need to create a file with UNIX type of line termination, then we set the property to "\n"
If the NewLine property is not set, the default newline
character("\r\n") is used.
Sample Code
to Write Unix Type File in C#
|
using System;
using System.Text;
using System.IO;
namespace UnixFile
{
class Program
{
static
void Main(string[]
args)
{
//Data
for the text file, is stored inside a string array
string[]
lines = { "First Line", "Second Line" };
//Variable
fileDetails contains the file name and path
String
fileNameAndPath = "C:\\Sample Text
File.txt";
//Below
line of code will delete the file if it already exists (OPTIONAL)
if (File.Exists(fileNameAndPath)) { File.Delete(fileNameAndPath); }
using
(TextWriter objFile = new StreamWriter(fileNameAndPath))
{
//Set
the New line Property to Unix type of New line
objFile.NewLine = "\n";
objFile.WriteLine(lines[0]);
objFile.WriteLine(lines[1]);
}
}
}
}
|
Note - When we create the file using above if we open in windows, then it
will be displayed as –
Instead open in Notepad++ or any suitable Editors, In NPP it will
displayed as –
Links –
TextWriter.NewLine
Property
No comments:
Post a Comment