I write some codes for simple text editor in C# and I use rich text box control, I found a problem that I can't solve. The problem is when I save a file in my text editor and then try to reopen it using windows notepad, it become in one line, this is the example
This is when I write and save from my app
After I save it and open in windows notepad it becomes like this
here are my code for saving a fie
try
{
saveFileDialog1.ShowDialog();
this.Text = file = toolStripTextBox1.Text = saveFileDialog1.FileName;
isi = richTextBox1.Text;
write = new System.IO.StreamWriter(file);
write.WriteLine(isi);
write.Close();
toolStripStatusLabel2.Text = "Saved";
}
catch (Exception)
{
toolStripStatusLabel2.Text = "Save cancelled by user";
}
do you have any idea how to fix it?
You are probably getting this because you are trying to save richTextBox1.Text (the whole text) in one line only using the following code
isi = richTextBox1.Text;
write = new System.IO.StreamWriter(file);
write.WriteLine(isi);
write.Close();
It's recommended to use write.WriteLine() on a specific line number in richTextBox1 then move to another line.
Example
for (int i = 0; i < richTextBox1.Lines.Length; i++)
{
write.WriteLine(richTextBox1.Lines[i]);
}
write.Close();
Another Solution
There's already a built-in function for RichTextBox to save a file with a specific encoding. You may use RichTextBox.SaveFile() for this purpose.
Example
RichTextBox.SaveFile(string path, RichTextBoxStreamType);
Where path represents saveFileDialog1.FileName in your code. For RichTextBoxStreamType, it's best to set it as RichTextBoxStreamType.PlainText as long as you do not use RTF such as Color/Font/Protection/Indent/etc...
Then, you may read the file again using the following method
RichTextBox.LoadFile(string path, RichTextBoxStreamType);
NOTICE: If the file is not in RTF and you try to read it in RTF (RichTextBox.LoadFile(string path, RichTextBoxStreamType.RichText);)
you may encounter formatting errors. In this case, you'll need to catch the exception and read the file in a Plain or Unicode encoding.
Example
RichTextBox _RichTextBox = new RichTextBox();
try
{
_RichTextBox.LoadFile(#"D:\Resources\text.txt", RichTextBoxStreamType.RichText);
}
catch (Exception EX)
{
if (EX.Message.ToLower().Contains("format is not valid"))
{
_RichTextBox.LoadFile(#"D:\Resources\text.txt", RichTextBoxStreamType.PlainText);
}
}
Thanks,
I hope you find this helpful :)
Saves the contents of the RichTextBox to a file by using richtextbox 's own save method: SaveFile(string, RichTextBoxStreamType);
you can refer this : http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.savefile%28VS.71%29.aspx
load the content of file by LoadFile(Stream, RichTextBoxStreamType);, refer this: http://msdn.microsoft.com/en-us/library/system.windows.forms.richtextbox.loadfile(v=vs.71).aspx
Related
I'm building a website in ASP.net and, in this case, I'm simply trying to read a .txt file and output it into a textbox whenever that page loads. I wrote this code so I could execute my idea:
protected void Page_Load(object sender, EventArgs e)
{
foreach (string line in System.IO.File.ReadLines(#"file_path"))
{
TextBox1.Text = line;
}
}
However, this is not working, as when I execute the website on this page, nothing loads. There is no exception that is being called or any error.
What can I do?
If you need more details or information, please don't refrain from asking.
Edit: I think it's important to say that I've tested doing
TextBox1.Text = "Hello World";
And that worked properly.
Well, to read the text, this works:
string sFile = #"C:\TEST2\T.txt";
string sTextData = File.ReadAllText(sFile);
TextBox1.Text = sTextData;
And if some some reason, you LEFT OUT some HUGE MASSIVE WHOPPER detail, say like you only want the first line of text from the file?
Then this:
string sFile = #"C:\TEST2\T.txt";
string sTextData = File.ReadAllText(sFile);
string strFirstLine = sTextData.Split(System.Environment.NewLine.ToCharArray())[0];
TextBox1.Text = strFirstLine;
FYI:
Don't forget to set the text box to multiline if you need/want to have more then one line of text display in that box.
As pointed out, we can use this:
File.ReadAllLines(sFile).FirstOrDefault();
however, the above still reads the whole text file.
If the text file is to be large, and we still want the first line, or wish to read + process line by line, then this is better:
StreamReader sR = new StreamReader(sFile);
int i = 0;
while (!sR.EndOfStream)
{
i++;
Debug.Print(i.ToString() + "->" + sR.ReadLine());
if (i >= 1)
break;
}
sR.Close();
So, above would read line by line, and if the text file was large, or we wish to only pull + read the first line from the file? Then of course the above example is better, since only the first line (or several lines if i condition is changed) is better from a performance + io point of view.
To read the first line, you can simply write this File.ReadLines(“YourFileName”).FirstOrDefault;
You need to use the method File.ReadAllText. It reruns the string value. And you can then assign to Text property.
File.ReadLines returns Ienumerable<string> not string .
my client wants me to do one task. which is whenever I print ctrl+P from the browser it will go automatically that contents to the database which is sql.
Now, Let me explain what I have tried to achieve this. Usually printerPlusPlus which is third party tool. Which adds virtual printer and prints the files PS to the temp directory than I can read the contents of that postscript file and save it to the database.
My real question is there anything from which I can convert this post script files to text or read them and save the texts to the database?
Or is there any better way to achieve this task?
Ghostscript is the alternate and ow-some feature to convert the postscripts to the text or pdf. But, I am completely clueless about the documentation and how to execute their commands.
_viewer.Interpreter.RunFile("C:\\PrinterPlusPlus\\Temp\\ankit_SONY-VAIO_sony_20151227_185020_3.ps");
GhostscriptPngDevice dev = new GhostscriptPngDevice(GhostscriptPngDeviceType.Png16m);
dev.GraphicsAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.TextAlphaBits = GhostscriptImageDeviceAlphaBits.V_4;
dev.ResolutionXY = new GhostscriptImageDeviceResolution(96, 96);
dev.InputFiles.Add(#"C:\\PrinterPlusPlus\\Temp\\ankit_SONY-VAIO_sony_20151227_185020_3.ps");
dev.OutputPath = #"C:\\PrinterPlusPlus\\Temp\\ankit_SONY-VAIO_sony_20151227_185020_3.txt";
dev.Process();
_preview.Activate();
I tried this but this seems to be not working and adding ASCII text to the txt file.
I found ghostscript little confusing. But, I found the solution from here
string inputFile = #"E:\gss_test\test_postscript.ps";
GhostscriptPipedOutput gsPipedOutput = new GhostscriptPipedOutput();
// pipe handle format: %handle%hexvalue
string outputPipeHandle = "%handle%" + int.Parse(gsPipedOutput.ClientHandle).ToString("X2");
using (GhostscriptProcessor processor = new GhostscriptProcessor())
{
List<string> switches = new List<string>();
switches.Add("-empty");
switches.Add("-dQUIET");
switches.Add("-dSAFER");
switches.Add("-dBATCH");
switches.Add("-dNOPAUSE");
switches.Add("-dNOPROMPT");
switches.Add("-sDEVICE=pdfwrite");
switches.Add("-o" + outputPipeHandle);
switches.Add("-q");
switches.Add("-f");
switches.Add(inputFile);
try
{
processor.StartProcessing(switches.ToArray(), null);
byte[] rawDocumentData = gsPipedOutput.Data;
//if (writeToDatabase)
//{
// Database.ExecSP("add_document", rawDocumentData);
//}
//else if (writeToDisk)
//{
// File.WriteAllBytes(#"E:\gss_test\output\test_piped_output.pdf", rawDocumentData);
//}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
finally
{
gsPipedOutput.Dispose();
gsPipedOutput = null;
}
}
This reads the postscript files easily :)
I have a rich text editor that I have created in C#. One of the features I am now trying to add is templates. I do not want the user to have to use an OpenFileDialog to navigate to the template and open the file. I would like to specify the filepath myself so that the user only has to click one button in order to open the template.
Currently, I am trying to achieve this using the following code:
private void formalLetterToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
try
{
if (richTextBoxPrintCtrl1.Modified == true);
{
NewFile();
}
richTextBoxPrintCtrl1.Rtf = fileContents;
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
However, whenever I try to open the template, I get an exception that is as follows:
System.ArgumentsException: File format is not valid.
However, I have tried to open the file using my OpenFileDialog and that works fine. Could somebody assist me in getting this working correctly?
Your problem is that you're trying to convert the file to a string using str = fileStream.ToString(); however, this converts the filestream to a string which is not the same thing.
Instead just do string fileContents = File.ReadAllText(filepath); to get all of the files contents into a string. You only need to use a FileStream/StreamReader if you're going to do some type of processing on the file.
Also, your use of the FileStream is a little off. I think what you really want is a StreamReader with something like this (example from msdn);
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
A FileStream cannot be used to read a file. It must be passed to a StreamReader in order to actually read the file and in this case there is no point in doing that because there is an overload of the constructor which takes a filepath. It's only useful if you don't know what kind of stream the reader is going to be reading.
Where you have;
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
You actually just want thins line; string fileContents = File.ReadAllText(filepath); , nothing else. There is no need for a FileStream when you're just reading all the text into a string.
You are making very heavy weather of loading RTF. Your code to read a file into a string will never work, as #evanmcdonnal explained. Did your file dialog based code that succeeded really do it like that? Remember that a file dialog is just UI that generates a file name in a string. If your code with a file dialog works, then it will work when the file dialog is replaced with a hard coded string.
I suspect that some part of your problem is that you are using a relative path. Perhaps the working directory is not what you expect it to be. You should specify the full path to the file.
In any case, to load RTF simply call the LoadFile method of the control. But I strongly recommend passing the full path to the file.
richTextBoxPrintCtrl1.LoadFile(fullPathToRtfFile);
I am a newbie to C#, I have a "Save to File" option in my program which saves the output of a richtextbox in a word document and when the user chooses this option, I have used saveFileDialogue box for the user to chose the filename and the location.
What I want is that every time when the user chooses this option the word document in which the output is saved has a pre-defined header and footer images...
Thanks a lot for your help in advance!
below is my 'Save to File" code.
private void menuItem7_Click(object sender, EventArgs e)
{
// Create a SaveFileDialog to request a path and file name to save to.
SaveFileDialog saveFile1 = new SaveFileDialog();
// Initialize the SaveFileDialog to specify the RTF extension for the file.
saveFile1.DefaultExt = "*.rtf";
saveFile1.Filter = "RTF Files|*.rtf";
// Determine if the user selected a file name from the saveFileDialog.
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
// Save the contents of the RichTextBox into the file.
richTextBox1.SaveFile(saveFile1.FileName,
RichTextBoxStreamType.PlainText);
}
}
First of all, create a function to take an image, width and height and return the rtf:
This is for a png
public string GetImage(string path, int width, int height)
{
var stream = new MemoryStream();
var img = Image.FromFile(path);
img.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
var bytes = stream.ToArray();
var str = BitConverter.ToString(bytes, 0).Replace("-", string.Empty);
var mpic = #"{\pict\pngblip\picw" + img.Width.ToString() + #"\pich" + img.Height.ToString() +
#"\picwgoa" + width.ToString() + #"\pichgoa" + height.ToString() +
#"\hex " + str + "}";
return mpic;
}
Now you need to insert this 'image' into the right place in the rtf. If you open your rtf file in notepad you should see something like this:
{\rtf1\ansi\ansicpg1252\deff0\deflang2057{\fonttbl{\f0\fnil\fcharset0
Microsoft Sans Serif;}} \viewkind4\uc1\pard\f0\fs17 MYTEXT\par }
If you wanted a quick and dirty method then get the rtf from the richTextBox into a string,
and insert your header image string after the deflang2057 followed by a '/par' to make a new line. Then insert your footer image string just before the closing '}'
something like this:
// Determine if the user selected a file name from the saveFileDialog.
if (saveFile1.ShowDialog() == System.Windows.Forms.DialogResult.OK &&
saveFile1.FileName.Length > 0)
{
var rtf = richTextBox1.Rtf.Insert(richTextBox1.Rtf.IndexOf("deflang2057") + 11, GetImage(#"c:\a.png", 5, 5) + #"\par");
using (var rtfFile = new StreamWriter(saveFile1.FileName))
{
rtfFile.Write(rtf);
}
}
I hope that gets you started.
Here is an example how to use Open XML SDK ...
Source Code
you will have to plug-in your text where it says "Original Text Here".
You have picked a very difficult task for a "newbie". To mix images and text you will need a complex format like PostScript, PDF, DocX, or RTF. Controlling pagination, for example to specify your header and footer images only once and have them automatically show up on the top and bottom of each page, is an even more difficult task.
You have not given us enough information to tell you where to start. For example, what is "my program"? Is it like a word processor? You will have to use the System.Drawing.Printing.PrintDocument classes to define a print document, draw headers and footers when you reach the appropriate place on each page, perform line layout, breaks and pagination. This is a large job for a professional programmer.
Or do you just want to produce a file that another program can output, with headers and footers? You could output RTF; the specification is here. This is an easier task; you may be able to leverage exisiting RTF interpreters.
Or do you want to display these documents on-screen? Han's suggestion to use an existing application via automation is a good one.
Break your task into smaller requirements and investigate each requirement.
This question have been answered. I recommend sumit_programmers solution below. For now, I've removed my code, thinking it's more confusing than helpful. When I've developed it a bit further, perhaps I'll post my code here, with some comments.
You may also be interested in the answer to the question Save text from rich text box with C#. There is an answer that reminds of the accepted answer to this question. The code should work, but it's written by me, so there may be some errors or missing information.
Update: I have improved the code a bit (at least I think so). "Encoding.Default" seems to work with most common encodings, like ANSI. If the encoding is UTF-8 without byte order mark (BOM), it seems "Encoding.Default" doesn't work, though. For more information, go to informit.com/guides. Here's the code I'm using right now:
private void fileOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog dlgOpen = new OpenFileDialog())
{
try
{
// Available file extensions
dlgOpen.Filter = "All files(*.*)|*.*";
// Initial directory
dlgOpen.InitialDirectory = "D:";
// OpenFileDialog title
dlgOpen.Title = "Open";
// Show OpenFileDialog box
if (dlgOpen.ShowDialog() == DialogResult.OK)
{
// Create new StreamReader
StreamReader sr = new StreamReader(dlgOpen.FileName, Encoding.Default);
// Get all text from the file
string str = sr.ReadToEnd();
// Close the StreamReader
sr.Close();
// Show the text in the rich textbox rtbMain
rtbMain.Text = str;
}
}
catch (Exception errorMsg)
{
MessageBox.Show(errorMsg.Message);
}
}
}
Yes, you are getting that error as you are trying to access file that can't be loaded in Rich Text Box. If you want to load a .rtf file you need to add this line
richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.RichText);
and if you want to load .txt file, you need to add this
richTextBox1.LoadFile(dlg.FileName, RichTextBoxStreamType.PlainText);
Sample Code:
using (OpenFileDialog ofd = new OpenFileDialog())
{
try
{
ofd.Filter = "Text files (*.txt)|*.txt|RTF files (*.rtf)|*.rtf";
if (ofd.ShowDialog() == DialogResult.OK)
{
if (Path.GetExtension(ofd.FileName) == ".rtf")
{
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.RichText);
}
if (Path.GetExtension(ofd.FileName) == ".txt")
{
richTextBox1.LoadFile(ofd.FileName, RichTextBoxStreamType.PlainText);
}
}
}
catch (Exception ex)
{
}
}
Edit: Ok, if you want to open a plain text file, go back to my original solution.
You could just change the MessageBox.Show to the line:
rtfMain.Text = File.ReadAllText(dlg.FileName);
See the doc for ReadAllText for more info.
The try/catch bit is to avoid having your app crash due to unhandled errors (sometimes it might be the best thing to do to just let it crash, but even then you usually want to close it down in a somewhat controlled manner). Especially when working with files, there's a high risk that they'll fail to load for some reason so it might be useful to surround the code with some error handling, for example something like this:
try
{
rtfMain.Text = File.ReadAllText(dlg.FileName);
}
catch(Exception ex) // should try to avoid catching generic Exception here and use a more specialized one
{
MessageBox.Show("Failed to open file. Error: " + ex.Message);
}
Old answer below
Edit: I forgot that it's a RichTextBox, so my first answer wasn't as suitable, so it's probably better to do this instead:
You could just change the MessageBox.Show to the line:
rtfMain.LoadFile(dlg.FileName);
Probably adding in suitable try/catch to handle any errors in reading the file.
See the documentation for RichTextBox.LoadFile for a complete sample.
try
{
openFileDialog fd=new openFileDialog();
fd.showDialog();
richTextbox1.LoadFile(fd.FileName);
}
catch(Exception exc)
{
MessageBox.Show(exc.Message);
}