With StreamWriter doesn't work \n (C#) - c#

I have a problem with the C# Stream Writer.
I use the following Code:
//Constructor
public EditorTXTFile
{
FileStream f = File.Create(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt");
f.Close();
}
//Function AddText
public void AddLogFileText(string text)
{
string text = "l1\n\rl2\n\rl3\n\nl5";
StreamWriter writer = new StreamWriter(System.IO.Directory.GetCurrentDirectory() + "\\Output.txt", true);
writer.Write(text);
writer.Close();
}
When I open Output.txt it shows for \n or \r a █(which means not showable symbol) and the whole string is in one line...
Later should the text hand over the function, so I can't write the text with .WriteLine because I don't know if the actual string is on the same line or in a new line.
What make I wrong?
Thanks for any help.

Use Environment.NewLine as line separator or "\r\n" if you want to do it by hand.

Line Separator(newLine) is \r\n not \n\r,
change your text as :
string text = "l1\r\nl2\r\nl3\r\nl5";

Try string text = #"l1\n\rl2\n\rl3\n\nl5";. To prevent character stuffing.

This is binary format:
writer.Write(text);
This is line sequential format:
writer.WriteLine(text);
You have to use WriteLine format...

You can use Environment.NewLine like this:
streamWriter.Write(String.Concat(Enumerable.Repeat(Environment.NewLine, n).ToArray()));

i tried to write a class and seprate "\n"s
but i found rich text box!!
yeah! it works:
RichTextBox rch = new RichTextBox();
rch.Text = cmn;
foreach (string l in rch.Lines)
strw.WriteLine(l);

Related

How to Pass this parameter?

I have trying to mirror the output screen to .txt file.By my below code i can able to mirror the output screen to text file. When executing the obj.OutputFile("First text"); there is no problem But some times i need print like obj.OutputFile("Second text {0}",text);
I got the exception during the second line execution
No overload for method 'OutputFile' takes 2 arguments test document
How do i clear my exception?
I want to my code which is to be accept different number of arguments passing.
My Code
class Program
{
static void Main(string[] args)
{
string text = "Sample";
Program obj = new Program();
obj.OutputFile("First text");
obj.OutputFile("Second text {0}",text);
Console.ReadKey();
}
public void OutputFile(string text)
{
string path = "Example.txt";
if (!File.Exists(path))
{
using (TextWriter tw = new StreamWriter(path))
{
tw.WriteLine(text);
Console.WriteLine(text);
}
}
else if (File.Exists(path))
{
using (TextWriter tw = new StreamWriter(path,true))
{
tw.WriteLine(text);
Console.WriteLine(text);
}
}
}
}
I am totally new to this c#. So i hope your answer would be simple.
Your call for OutputFile doesn't seem correct. You have obj.OutputFile("Second text {0}",text); while the method signature is public void OutputFile(string text), which means it requires one parameter.
All you have to do is to change your call to:
obj.OutputFile(string.Format("Second text {0}", text));
And if you are using C# 6 you can make it even better:
obj.OutputFile($"Second text {text}");
change
obj.OutputFile("Second text {0}",text);
to
obj.OutputFile(string.Format("Second text {0}",text));
EDIT:
Your function definition for OutputFile has one parameter. With the comma between the strings you have two parameters instead of the expected one parameter.

How read form file Text language Arabic

I have a text file that contains a single word but it is with language : Arabic
I want to extract it
My code is:
string text = System.IO.File.ReadAllText(#"C:\CINPROCESSING\nom.txt");
Console.WriteLine(text );
I have the result with unknown characters : ????
How i can fix it?
Thanks,
Setup right codepage for your text.
System.IO.File.ReadAllText(#"C:\CINPROCESSING\nom.txt",System.Text.Encoding.GetEncoding(codepage))
May be codepage=1256 (windows-arabic).
Your code reads the text correctly into the variable text. (Debug and See)
However, dispalying arabic characters in the windows Console is another issue (Check how to solve it Here)
You can try this:
string text = System.IO.File.ReadAllText(#"C:\CINPROCESSING\nom.txt",Encoding.Default);
Console.WriteLine(text);
Try specifying the encoding using this StreamReader constructor:
StreamReader arabic_reader = new StreamReader(filePath, System.Text.Encoding.UTF8, true);
OR
string text = System.IO.File.ReadAllText(#"C:\CINPROCESSING\nom.txt",Encoding.UTF8);
Try :
StreamReader reader = new StreamReader(filePath, System.Text.Encoding.UTF8, true);
For reference: http://msdn.microsoft.com/en-us/library/ms143457.aspx

Find regex in file with StreamReader and overwrite it with StreamWriter

I am reading text file with StreamReader and doing Regex.Match to find specific info, now when I found it I want to replace it with Regex.Replace and I want to write this replacement back to the file.
this is text inside my file:
///
/// <Command Name="Press_Button" Comment="Press button" Security="Security1">
///
/// <Command Name="Create_Button" Comment="Create button" Security="Security3">
/// ... lots of other Commands
now I need to find : Security="Security3"> in Create_Button command, change it to Security="Security2"> and write it back to the file
do {
// read line by line
string ReadLine = InfoStreamReader.ReadLine();
if (ReadLine.Contains("<Command Name"))
{
// now I need to find Security1, replace it with Security2 and write back to the file
}
}
while (!InfoStreamReader.EndOfStream);
any ideas are welcome...
EDITED:
Good call was from tnw to read and write to the file line by line. Need an example.
I'd do something more like this. You can't directly write to a line in the file like you're describing there.
This doesn't use regex but accomplishes the same thing.
var fileContents = System.IO.File.ReadAllText(#"<File Path>");
fileContents = fileContents.Replace("Security1", "Security2");
System.IO.File.WriteAllText(#"<File Path>", fileContents);
Pulled pretty much directly from here: c# replace string within file
Alternatively, you could loop thru and read your file line-by-line and write it line-by-line to a new file. For each line, you could check for Security1, replace it, and then write it to the new file.
For example:
StringBuilder newFile = new StringBuilder();
string temp = "";
string[] file = File.ReadAllLines(#"<File Path>");
foreach (string line in file)
{
if (line.Contains("Security1"))
{
temp = line.Replace("Security1", "Security2");
newFile.Append(temp + "\r\n");
continue;
}
newFile.Append(line + "\r\n");
}
File.WriteAllText(#"<File Path>", newFile.ToString());
Source: how to edit a line from a text file using c#

C# method to read text error log file

I am trying to read a file I create that contains all the logs lines throughout my program. I have the following cod:
private string ReadEmailLog(string EmailLog)
{
TextReader tr = new StreamReader(EmailLog);
tr.ReadLine();
tr.Close();
}
I need to read the EmailLog file, every line of it, and then put return it into a string called message. How would I get this method to return the whole log file, every line?
You can use File.ReadAllText or File.ReadAllLines.
If you're using .NET 4.0, you can also use File.ReadLines:
var files = from file in Directory.EnumerateFiles(#"c:\",
"*.txt", SearchOption.AllDirectories)
from line in File.ReadLines(file)
where line.Contains("Microsoft")
select new
{
File = file,
Line = line
};
foreach (var f in files)
{
Console.WriteLine("{0}\t{1}", f.File, f.Line);
}
This allows you to make file I/O part of a LINQ operation.
Try
tr.ReadToEnd();
which will return a string that contains all the content of your file.
TextReader.ReadToEnd Method
If you want to get the lines in a string[], then
tr.ReadToEnd().Split("\n");
should do it, while it will separate the lines to the "\n" character, which represents a carriage return and line feed combined characters (new line character).
simply use:
String text = tr.ReadToEnd();
You can read all the contents or the log and return it. For example:
private string void ReadEmailLog(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
return logreader.ReadToEnd();
}
}
Or if you want each line one at a time:
private IEnumerable<string> ReadEmailLogLines(string EmailLog)
{
using(StreamReader logreader = new StreamReader(EmailLog))
{
string line = logreader.ReadLine();
while(line != null)
{
yield return line;
}
}
}
tr.ReadToEnd(); //read whole file at once
// or line by line
While ( ! tr.EOF)
tr.ReadLine()//

How can I edit a text file using C#?

Lets say i have a text file with following content:
Hello!
How are you?
I want to call the file via a simple application that produces an output file with the following contents:
buildLetter.Append("Hello!").AppendLine();
buildLetter.Append("How are you?").AppendLine();
As you see, every line should be put between " ".
Any help will be appreciated.
void ConvertFile(string inPath, string outPath)
{
using (var reader = new StreamReader(inPath))
using (var writer = new StreamWriter (outPath))
{
string line = reader.ReadLine();
while (line != null)
{
writer.WriteLine("buildLetter.Append(\"{0}\").AppendLine();",line.Trim());
line = reader.ReadLine ();
}
}
}
You should add some I/O exception handling on your own.
If you want to append "" to each line you could try combining the ReadAllLines and WriteAllLines methods:
File.WriteAllLines(
"output.txt",
File
.ReadAllLines("input.txt")
.Select(line => string.Format("\"{0}\"", line))
.ToArray()
);
Notice that this loads the whole file contents into memory so it wouldn't work well with very large files. In this case stream readers and writers are more adapted.
Use the StreamReader class from System.IO
Refer this link for sample code
All you probably need to do is change the line
Console.WriteLine(sr.ReadLine());
to
Console.WriteLine(""""" + sr.ReadLine() + """""); // handwritten code - not tested :-)
For a small text files this works for me.
private void EditFile(string path, string oldText, string newText)
{
string content = File.ReadAllText(path);
content = contenido.Replace(oldText, newText);
File.WriteAllText(path, content);
}

Categories