StreamReader adds unwanted backslashes - c#

I am reading a file that contains other file paths and i am putting it into a StringReader:
var inputReader = new StreamReader(input);
var reader = new StringReader(inputReader.ReadToEnd());
When i debug the StreamReader.ReadToEnd() and look at the whole text everything seems right. The paths have this form: C:\\User\\ ....
However when i now read each line in the file with:
string line = reader.ReadLine();
The paths have the following form: C:\\\\User\\\\ ....
Any suggestions on how to fix that? Thank you in advance!

Related

C# creating Word file - Error opening file

I am creating some word files (and replacing some words) from word template using this code snippet:
File.Copy(sourceFile, destinationFile, true);
try
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(destinationFile, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
foreach (KeyValuePair<string, string> item in keyValues)
{
Regex regexText = new Regex(item.Key);
docText = regexText.Replace(docText, item.Value);
}
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
But when I am trying to open the produced file I get this error:
We're sorry. We can't open XXX.docx because we found a problem with its contents
XML parsing error Location:Part:/word/document.xml, Line:2, Column:33686
Here are the contents of document.xml in the specific place:
.....<w:szCs w:val="20"/><w:lang w:val="en-US"/></w:rPr><w:t> </w:t></w:r><w:proofErr w:type="spellEnd"/>....
Where 33686 is the position of the &nbsp. How I can fix that problem?
EDIT In another file that produced correctly in the same position there are some random characters I used for testing which are used also in the title of the document
It looks like you're using regular expressions to directly modify XML, which is typically going to lead to difficult-to-troubleshoot issues like this, especially if any of your regexes match anything that could be interpreted as XML.
As an alternative, you may want to investigate that WordProcessDocument class more deeply. It looks like it has strongly-typed objects like Paragraph that you can modify more safely.

Special character not reading in .txt file

I am using stream reader for reading a text file.
This is the contents of the .txt file:
</a> Schools's are a suitable public </a>
When I read that text I got:
<a>Schoolss are a suitable public<a>
As you can see I did't receive the quotation. How can I receive the special character in a stream reader?
I used following code:
using (StreamReader reader = new StreamReader(CommonGetSet.FileName, System.Text.Encoding.ASCII))
{
string text = reader.ReadToEnd();
docKeyword = XDocument.Parse(text);
}
The problem you are having is that you are trying to load a text file with an xml reader, i.e. this part:
XDocument.Load(reader);
If you look at this question: What characters do I need to escape in XML documents?, you will see other characters that will be stripped/need escaping too.
If you inspect the StreamReader in the debugger you will see it shows the correct text, something that the answer by #JinsPeter shows. So you need to read in a text file, the easiest way is to use either File.ReadAllText or File.ReadAllLines depending on whether you want the result as a string or string[] respectively:
string contents = File.ReadAllText(path);
string[] lines = File.ReadAllLines(path);
However, if for some reason you really want to use a StreamReader you can read directly from the stream using ReadToEnd, ReadLine or any other appropriate read method:
using (StreamReader reader = new StreamReader(path))
{
string contents = reader.ReadToEnd();
}
However, note that the StreamReader methods will read from the current position in the stream so you may need to set the position yourself.
For a list of other ways to read in a file in C# see this question: How to read an entire file to a string using C#?.
When I printed the same text inside the StreamReader I got the ' .
So the issue is with writing it to XML or HTML. Try to fix that rather than finding issue in StreamReader.
using (StreamReader inputStream = new StreamReader(filepath, System.Text.Encoding.UTF8))
{
string line = inputStream.ReadToEnd();
Console.WriteLine(line);
}

C# CSVWriter how to avoid getting empty line at the end of writing all lines to a file

I am using CSVWriter to write to csv by using the following link:
How to create csv with header and footer using LinqtoCsv or anything better in C#
But for some reason i am getting an empty line created at the end. Can anyone help me what am i doing wrong or how can i avoid getting an empty line?
Here is the code to create csv using csvwriter:
using (var writer = File.AppendText(outputCsv))
{
var csv = new CsvWriter(writer);
csv.Configuration.RegisterClassMap<CustomMap>();
csv.Configuration.HasHeaderRecord = true;
csv.Configuration.QuoteNoFields = true;
csv.Configuration.Delimiter = "|";
csv.WriteRecords(asRunLogs.ToList());
csv.WriteRecord(new CSVFooterRecord()
{
FooterText =
$"TRAILER:{"qsaam_promos.csv"}|{DateTime.Now.ToString("ddMMyyHHmm")}|{asRunLogs.Count}"
});
}
When i open the file in Notepad++, i can see an empty line at the end.
Appreciate help with regard to this.
Thanks
You could do
writer.Write($"TRAILER:{"qsaam_promos.csv"}|{DateTime.Now.ToString("ddMMyyHHmm")}|{asRunLogs.Count}");
writer.Flush();
instead of
csv.WriteRecord(new CSVFooterRecord()
{
FooterText =
$"TRAILER:{"qsaam_promos.csv"}|{DateTime.Now.ToString("ddMMyyHHmm")}|{asRunLogs.Count}"
});

StreamReader read file and StreamWriter write that result omitting first line?

Using the following code:
string lines = "";
using (StreamReader sr = new StreamReader(#"file.txt"))
{
lines = sr.ReadLine();
}
using (StreamWriter writer = new StreamWriter(#"file.txt"))
{
writer.Write(lines); // Change this to skip the first line
}
How can I make it rewrite everything EXCEPT the first line?
Maybe you can try this:
var lines = File.ReadLines("file.txt").Skip(1).ToList();
File.WriteAllLines("file.txt",lines);
It will write all the lines to your file except the first line and replace your file content.So basically it will remove the first line from your file.
var allLinesExceptFirstOne = System.IO.File.ReadAllLines(filename).Skip(1).ToList();

How to write a text file after the previous line in C#?

My below code creates a txt file and writes something to that file. But I need to write a new line after the previous lines when I run the script several times. Code:
string filePath = "D:\\DOT_NET\\C#\\abc.txt";
FileInfo t = new FileInfo(filePath);
StreamWriter Tex = t.CreateText();
Tex.WriteLine("Hi freinds");
Tex.WriteLine("csharpfriends is the new url for c-sharp");
Tex.Write(Tex.NewLine);
Tex.Close();
Current output on the abc.txt file:
Hi friends
csharpfriends is the new url for c-sharp
But I need the output if I run the script several times to be this:
Hi friends
csharpfriends is the new url for c-sharp
Hi friends
csharpfriends is the new url for c-sharp
Hi friends
csharpfriends is the new url for c-sharp
How can I do that? Please help.
StreamWriter has a constructor which lets you append text instead of just writing into the file. The constructor is
new StreamWriter(string filepath, bool append)
If you set that bool to "true", then all writing will be at the end of the document. In your example...
StreamWriter Tex = new StreamWriter(#"D:\DOT_NET\C#\abc.txt", true);
using (StreamWriter sw = File.AppendText(path))
{
sw.WriteLine("...");
}
Try this:
System.IO.File.WriteAllText(#"file_location", System.IO.File.ReadAllText(#"file_location") + System.Environment.NewLine + "The_new_text");
That will add a new text to the next line.

Categories