How to write a text file after the previous line in C#? - 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.

Related

Convert bytes to PDF File

I am able to create a word doc using the code below.
Question: how do i create a pdf instead of word doc?
Code
using (StreamWriter outputFile = new StreamWriter(Path.Combine(docPath, tdindb.TDCode + "-test.doc")))
{
string html = string.Format("<html>{0}</html>", sbHtml);
outputFile.WriteLine(html);
}
string FileLocation = docPath + "\\" + tdindb.TDCode + "-test.doc";
byte[] fileBytes = System.IO.File.ReadAllBytes(FileLocation);
string fileName = Path.GetFileName(FileLocation);
return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName);
Thank you
You need to use one of PDF creating libraries. I tried to use iText , IronPDF, and PDFFlow. All of them create PDF documents from scratch.
But PDFFlow was better for my case because i needed automatic page creation and multi-page spread table)
This is how to create a simple PDF file in C#:
{
var DocumentBuilder.New()
.AddSection()
.AddParagraphToSection("your text goes here!")
.ToSection()
.ToDocument()
.Build("Result.PDF");
}
feel free to ask me if you need more help.
Converting a Word document to HTML has been answered here before. The linked example is the first result of many on this site.
Once you have your HTML, to create a PDF you need to use a PDF creation library. For this example we will use IronPDF which requires just 3 lines of code:
string html = string.Format("<html>{0}</html>", sbHtml);
var renderer = new IronPdf.ChromePdfRenderer();
// Save PDF file to BinaryData
renderer.RenderHtmlAsPdf(html).BinaryData;
// Save file to location
renderer.RenderHtmlAsPdf(html).SaveAs("output.pdf");

StreamReader adds unwanted backslashes

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!

c# copy from text file to word document

I want to copy data from text file to word file. I already have tried it with different alternatives like string array, StringBuilder and StreamReader using Interop which works good, but it takes too much time. It would really be thankful if anyone can suggest me with a better one. Been through many forms on the web, but couldn't find.
FYI: My text file contains more than 1,00,000 lines.
This is one of which I have tried:
string[] lines = File.ReadAllLines(path); //path is text file path
var doc = new MSWord.Document();
foreach (string lin in lines)
{
doc.Content.Text += lin.ToString();
}
doc.Save();
Well, this works good but takes a lot of time and also sometimes throws an error like:
Unhandled Exception: System.Runtime.InteropServices.COMException: Word has encountered a problem.
static void Main(string[] args)
{
Word.Application wordApp = new Word.Application();
Word.Document wordDoc = wordApp.Documents.Add();
Stopwatch sw = Stopwatch.StartNew();
System.Console.WriteLine("Starting");
string path = #"C:\";
StringBuilder stringBuilder = new StringBuilder();
using (FileStream fs = File.Open(path + "\\big.txt", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (BufferedStream bs = new BufferedStream(fs))
using (StreamReader sr = new StreamReader(bs))
{
wordDoc.Content.Text = sr.ReadToEnd();
wordDoc.SaveAs("big.docx");
}
sw.Stop();
System.Console.WriteLine($"Complete Time :{sw.ElapsedMilliseconds}");
System.Console.ReadKey();
}
Output :
Starting
Complete Time :5556
Or You can use Parallel :
using (StreamReader sr = new StreamReader(bs))
{
Parallel.ForEach(sr.ReadToEnd(), i=>
{
stringBuilder.Append(i);
});
wordDoc.Content.Text = stringBuilder.ToString();
wordDoc.SaveAs(path + "\\big3.docx");
}
Output:
Starting
Complete Time :2587
Microsoft Word can read text files - so why not read the text file into an Interop Word Document & then convert by using one of the SaveAs methods.
I tested with a 34Mb, 1000000 line text file - the result was a 22Mb DOCX file:
MSWord.Application appAC = new MSWord.Application();
MSWord.Document doc = appAC.Documents.Open("TestRead.txt");
doc.SaveAs2(FileName:"TestSave", FileFormat:WdSaveFormat.wdFormatDocumentDefault);
doc.Close();
appAC.Quit();
Note that Microsoft states a maximum document size of 32MB - the text file exceeded this, but the resulting DOCX file was smaller - your exception maybe related to the size of the final file.

How to edit a file in IsolatedStorage C#

I have been fiddling with this problem for the past hour so I thought you guys may be able to help on a Friday afternoon!
Problem
I am trying to edit an XML file in localstorage but can't figure out how to edit the existing file and re-save the file. The edit I have made it to remove a certain node from the XML.
Code
Here is the method that does all the work.
This first code snippet was already in the code and basically creates the XML file and saves it to localstorage.:
protected byte[] CreateFileData(PortableBusinessObjects.Location location, string geoObjectFilename)
{
byte[] fileData = null;
var xmlFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".xml";
var zipFile = System.IO.Path.GetFileNameWithoutExtension(geoObjectFilename) + ".zip";
using (IsolatedStorageFileStream fileStream = localStorage.CreateFile(xmlFile))
{
XmlWriter writer = XmlWriter.Create(fileStream);
if (location.GetType() == typeof(PortableBusinessObjects.Shape))
_xmlShapeSerializer.Serialize(writer, location);
else if (location.GetType() == typeof(PortableBusinessObjects.Point))
_xmlPointSerializer.Serialize(writer, location);
fileStream.Flush();
fileStream.Close();
}
}
This is my attempt at overwriting the saved file (Doesn't work):
using (IsolatedStorageFileStream doc = localStorage.OpenFile(xmlFile, FileMode.Open))
{
System.Xml.Linq.XDocument test = System.Xml.Linq.XDocument.Load(doc);
test.Descendants("Time").Remove();
XmlWriter writer = XmlWriter.Create(doc);
doc.Flush();
doc.Close();
}
Question
Where do I place my code that removes the "Time" nodes and saves the file?
Your saving code doesn't do any saving - you just create an XmlWriter and do nothing with it.
There are various methods built into XDocument than can help you here. While you could pass your XmlWriter to it, you can actually save directly to the stream:
test.Save(doc);
Note you will need to move to the beginning of the stream before writing to it - loading your XML will have read to the end:
doc.Position = 0;
You should use the IsolatedStorageFileStream together with the StreamWriter.
See How to: Read and Write to Files in Isolated Storage
With XDocument you then have to Save() the new contents to the stream.

Use local file with StringReader

I'm developing an app for WP.
I'm using a XML file online, it's working fine but when I want to use the same XML file in local storing, this doesn't work...
I added it at my project.
To use it online, I'm using that :
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(new Uri("http://exemple.com/news.xml"), "News");
And in my function client_DownloadStringCompleted, I read like that:
StringReader stringReader = new StringReader(e.Result);
So this it's working but with my local file I'm doing like that directly and it's not working :
StringReader stringReader = new StringReader("news.xml");
Do you know how I can fix that ?
Thank you for your help.
EDIT :
It's ok, thanks for your help !
I wrote that :
var resource = Application.GetResourceStream(new Uri(#"/YOURASSEMBLYNAME;component/news.xml", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
StringReader stringReader = new StringReader(streamReader.ReadToEnd());
And I used the file like a resource.
The parameter of the StringReader constructor is the string that you want to read.
In the code that you have that does not work, you are reading the name of the file not the contents of the file.

Categories