Accessing the content of the file - c#

//Introduction
Hey, Welcome.....
This is the tutorial
//EndIntro
//Help1
Select a Stock
To use this software you first need to select the stock. To do that, simply enter the stock symbol in the stock text-box (such as "MSFT").
To continue enter "MSFT" in the stock symbol box.
//EndHelp1
//Help2
Download Stock Data
Next step is to to download the stock data from the online servers. To start the process simply press the "Update" button or hit the <ENTER> key.
After stock data is downloaded the "Refresh" button will appear instead. Press it when you want to refresh the data with the latest quote.
To continue make sure you are online and press the "Update" button
//EndHelp2
First time I want to display the content between //Introduction and //EndIntro then second time the content between //Help1 and //EndHelp1 and so on.

That's a very open-ended question - what sort of file? To read binary data from it you'd usually use:
using (Stream stream = File.OpenRead(filename))
{
// Read from the stream here
}
or
byte[] data = File.ReadAllBytes(filename);
To read text you could use any of:
using (TextReader reader = File.OpenText(filename))
{
// Read from the reader
}
or
string text = File.ReadAllText(filename);
or
string[] lines = File.ReadAllLines(filename);
If you could give more details about the kind of file you want to read, we could help you with more specific advice.
EDIT: To display content from an RTF file, I suggest you load it as text (but be careful of the encoding - I don't know what encoding RTF files use) and then display it in a RichTextBox control by setting the Rtf property. Make the control read-only to avoid the user editing the control (although if the user does edit the control, that wouldn't alter the file anyway).
If you only want to display part of the file, I suggest you load the file, find the relevant bit of text, and use it appropriately with the Rtf property. If you load the whole file as a single string you can use IndexOf and Substring to find the relevant start/end markers and take the substring between them; if you read the file as multiple lines you can look for the individual lines as start/end markers and then concatenate the content between them.
(I also suggest that next time you ask a question, you include this sort of detail to start with rather than us having to tease it out of you.)
EDIT: As Mark pointed out in a comment, RTF files should have a header section. What you've shown isn't really an RTF file in the first place - it's just plain text. If you really want RTF, you could have a header section and then the individual sections. A better alternative would probably be to have separate files for each section - it would be cleaner that way.

Not sure I understand your question correctly. But you can read and write content using System.IO.StreamReader and StreamWriter classes
string content = string.Empty;
using (StreamReader sr = new StreamReader("C:\\sample.txt"))
{
content = sr.ReadToEnd();
}
using (StreamWriter sw = new StreamWriter("C:\\Sample1.txt"))
{
sw.Write(content);
}

Your question needs more clarification. Look at System.IO.File for many ways to read data.
The easiest way of reading a text file is probably this:
string[] lines = File.ReadAllLines("filename.txt");
Note that this automatically handles closing the file so no using statement is need.
If the file is large or you don't need all lines you might prefer to reading the text file in a streaming manner:
using (StreamReader streamReader = File.OpenText(path))
{
while (true)
{
string line = streamReader.ReadLine();
if (line == null)
{
break;
}
// Do something with line...
}
}
If the file contains XML data you might want to open it using an XML parser:
XDocument doc = XDocument.Load("input.xml");
var nodes = doc.Descendants();
There are many, many other ways to read data from a file. Could you be more specific about what the file contains and what information you need to read?
Update: To read an RTF file and display it:
richTextBox.Rtf = File.ReadAllText("input.rtf");

Related

What is the correct encoding to read and write PostScript files

I would like to parse a PostScript file, find appropriate line number and insert a PostScript command. So, I need to read the whole file and write it as a new file along with the new commands I want to insert.
I'm using StreamReader and StreamWriter for this process.
StreamReader sr = new StreamReader("filename.ps", System.Text.Encoding.UTF8, true);
StreamWriter sw = new StreamWriter("updatedfilename.ps",true, System.Text.Encoding.UTF8);
When doing this, even though the commands are inserted in the appropriate location, some characters are getting lost due to encoding issues.
For example, please check the below image: In the After content, you can notice the yellow highlighted characters which got added during my write process.
In summary, I would like to know the process to read and write a PS file as it is without losing data because of encoding.

File.ReadAllText does not return full content in C#

In my c# program, I have an image which is successfully stored in a byte[] data called bytes. I successfully write it into a .txt file using the following code
using (FileStream file = new FileStream("text.txt", FileMode.Create, FileAccess.Write))
{
file.Write(bytes, 0, numToWrite);
file.Close();
}
The above code stores the exact content I wish to store.
Whenever I wish to read the content of the file, text.txt, into textbox I only get the first line or little part of the first line. But when I open the file, text.txt, I see the complete content.
This is the code I use to read the file
string kk = File.ReadAllText("text.txt");
You have said at the start of the question that you have a byte[] that you are writing into the file. It's not clear why you decided not to use File.WriteAllBytes but let's assume that your code is correctly writing all the data into the file called "text.txt", which has been explained in comments does not magically make this a text file.
Using File.ReadAllText is not going to work because The data in the file is binary data, not text. As you can see from the remarks on the documentation, it will try to decide the encoding of the text file (which won't work because it contains binary data) and will do end of line processing which you won't want for a binary file.
The best way to read the data back is to use File.ReadAllBytes, which gives you back a byte[], just like you started with.

Add text and picture in .docx file

I use a Office Word file (template) and in this file there is repetitive default text and photo that I have to replace it by another photo and text
How can I define specific zone in the template and then find those zones in C# to replace them ?
I think the best way is to find out how to manipulate the word xml structure to include the data you want.
For template filling and altering you can use the XML SDK from Microsoft
You can also follow this manual approach here without using the SDK.
Manual approach. You will add a custom XML Ressource that includes your changes/ressources for the template.
If you don`t need to be that flexible you can use the standard content control / picture content control in Word and replace them afterwards in C# - it depends how flexible you want to be in replacing elements..
You can find a good and complete example of using picture content control here: Picture content control handling
Ok, finally I try this approch ; use a Word file with Content Control and use a XML file to bind data to them
For that I use the following code :
string outFile = #"D:\template_created.docx";
string docPath = #"D:\template.docx";
string xmlPath = #"D:\template.xml";
File.Copy(docPath, outFile);
using (WordprocessingDocument doc = WordprocessingDocument.Open(outFile, true))
{
MainDocumentPart mdp = doc.MainDocumentPart;
if (mdp.CustomXmlParts != null)
{
mdp.DeleteParts<CustomXmlPart>(mdp.CustomXmlParts);
}
CustomXmlPart cxp = mdp.AddCustomXmlPart(CustomXmlPartType.CustomXml);
FileStream fs = null;
try
{
fs = new FileStream(xmlPath, FileMode.Open);
cxp.FeedData(fs);
mdp.Document.Save();
}
finally
{
if (fs != null)
{
fs.Dispose();
}
}
}
When I run the app, it created the custom XML file and append it to my Word file. When I open the Word file, there is no error, but all the Content Control are not filled
My final approach was to use Content Control in my Word document with a unique id. Then I can find those id's with C# and replace the content.

append text to lines in a CSV file

This question seems to have been asked a million times around the web, but I cannot find an answer which will work for me.
Basically, I have a CSV file which has a number of columns (say two). The program goes through each row in the CSV file, taking the first column value, then asks the user for the value to be placed in the second column. This is done on a handheld running Windows 6. I am developing using C#.
It seems a simple thing to do. But I cant seem to add text to a line.
I cant use OleDb, as System.Data.Oledb isnt in the .Net version I am using. I could use another CSV file, and when they complete each line, it writes it to another CSV file. But the problems with that are - The file thats produced at the end needs to contain EVERY line (so what if they pull the batterys out half way). And what if they go back, to continue doing this another time, how will the program know where to start back from.
For every row, open the output file, append the new row to it, and then close the output file. To restart, count the number of rows in the existing output file from the previous run, which will give you your starting in the input file (i.e., skip that number of rows in the input file).
Edit: right at the start, use System.IO.File.Copy to copy the input file to the output file, so you have all the file in case of failure. Now open the input file, read a line, convert it, use File.ReadAllLines to read ALL of the output file into an array, replace the line you have changed at the right index in the array, then use File.WriteAllLines to write out the new output file.
Something like this:
string inputFileName = ""; // Use a sensible file name.
string outputFileName = ""; // Use a sensible file name.
File.Copy(inputFileName, outputFileName, true);
using (StreamReader reader = new StreamReader(inputFileName))
{
string line = null;
int inputLinesIndex = 0;
while ((line = reader.ReadLine()) != null)
{
string convertedLine = ConvertLine(line);
string[] outputFileLines = File.ReadAllLines(outputFileName);
if (inputLinesIndex < outputFileLines.Length)
{
outputFileLines[inputLinesIndex] = convertedLine;
File.WriteAllLines(outputFileName, outputFileLines);
}
inputLinesIndex++;
}
}

Insert data into text file

I want to insert the data at some positions in the text file without actually overwriting on the existing data. I have two text file. "one.txt" file have 1000 lines, "two.txt" file have 10000 lines. I want to read "one.txt" file content and insert into first 1000 lines of "two.txt" file content(Append the content of "one.txt" to the beginning of "two.txt").
Criteria:
Minimum code .
Less Memory consumption(irrespective of programming language )
Performance (will be considered based on size of the file).
just open up a streamreader for the first file, and a stream writer (in append mode) for the second file. As your reading the first 1000 lines from the first file, insert them into the second.
Something like this:
StreamReader sr = new StreamReader("one.txt");
StreamWriter sw = new StreamWriter("two.txt", true); //true for append
index i = 0;
while (i < 1000) {
sw.WriteLine(sr.ReadLine());
i++;
}
You may want to check for end of file on the StreamReader, but this will give you the general idea....
Based on the new information in OP:
You can use this same type of method, but just create a brand new file, reading the data from the first file, followed by the data from the second file. Once it's inside the new file, replace the original "two.txt".
If you're not limited to c# you can just do the following from a windows command line:
copy one.txt + two.txt three.txt
This would create the file you want, but it would be called three.txt. If you must have it in two.txt, you could simply rename two.txt to something else first and then do the copy append with two.txt as the third parm.
If you only have to do this once, here is some code that will do what you want. I did not compile this, but I believe there are no issues.
string[] linesOne = File.ReadAllLines(pathToFile1);
string[] linesTwo = File.ReadAllLines(pathToFile2);
List<string> result = new List<string>();
for(int i=0;i<1000;i++)
{
result.Add(linesOne[i]);
}
result.AddRange(linesTwo);
File.WriteAllLines(pathToFile2, result);
Hope this gets you started.
Bob

Categories