I built a windows form application that opens any text file (even pdf using iTextSharp Dll) and view its contents in a rich tex box, a search field where i can search for a certain pattern, all possible matches to be highlighted in "Gold" color. I created a save button.
how can i overwrite the text file (.doc) with the text highlighted
by retaining the text format?
how can i do the same step with pdf?
(since pdf will crash after overwriting the file)
The code:
private void open_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
tb.Clear();
label1.Text = openFileDialog1.FileName;
if (label1.Text.Contains(".pdf"))
{
// create a reader (constructor overloaded for path to local file or URL)
string location = openFileDialog1.FileName;
PdfReader reader = new PdfReader(location);
StringBuilder text = new StringBuilder();
for (int page = 1; page <= reader.NumberOfPages; page++)
{
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
string currentText = PdfTextExtractor.GetTextFromPage(reader, page, strategy);
currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
text.Append(currentText);
reader.Close();
}
tb.Text = text.ToString();
}
else
{
tb.Text = File.ReadAllText(label1.Text);
}
}
}
private void save_Click(object sender, EventArgs e)
{
SaveFileDialog saveFile1 = new SaveFileDialog();
if (saveFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(saveFileDialog1.FileName, tb.Text);
}
}
private void search_Click(object sender, EventArgs e)
{
int index = 0;
while (index < tb.Text.LastIndexOf(sb.Text))
{
tb.Find(sb.Text,index,tb.TextLength,RichTextBoxFinds.None);
tb.SelectionBackColor = Color.Gold;
index = tb.Text.IndexOf(sb.Text, index) + 1;
}
}
Thanks in advance!
Can you please try using this to get text along with all rich text format codes?
string str = richTextBox.Rtf;
For more information and implementation guidelines with respect to this context, please refer
http://www.codeproject.com/Articles/12932/Saving-and-Restoring-RichTextBox-Formatted-Text-Al
Related
I couldn't find any method to add in the if statement to read a text file. Here is the code;
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog BrowseFile1 = new OpenFileDialog();
BrowseFile1.Title = "Select a text file";
BrowseFile1.Filter = "Text File |*.txt";
BrowseFile1.FilterIndex = 1;
string ContainingFolder = AppDomain.CurrentDomain.BaseDirectory;
BrowseFile1.InitialDirectory = #ContainingFolder;
//BrowseFile1.InitialDirectory = #"C:\";
BrowseFile1.RestoreDirectory = true;
if (BrowseFile1.ShowDialog() == DialogResult.OK)
{
}
I just wanna get whole text froma text file that I choose from this OpenFolderDialog window.
string text = System.IO.File.ReadAllText(BrowseFile1.FileName);
Another possibility is using a StreamReader:
http://msdn.microsoft.com/en-us/library/db5x7c0d(v=vs.110).aspx
Just Change the file locatations through BrowseFile1.FileName.
I am making a WPF program, and right now I want to be able to open and merge files. I have a button to open a file and I have a button to merge the file, and when I don't implement the "onTextChanged" method both buttons work properly and the files are formatted properly. But if I implement the onTextChanged method and use the merge file button, the previous 'file' gets extra lines in its output.
Open Button Code:
private void Button_Click_1(object sender, RoutedEventArgs e)
{
//Open windows explorer to find file
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
//clears the buffer to open new file
buffer.Clear();
//string to hold line from file
string text;
// Read the file and add it line by line to buffer.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text);
}
//close the open file
file.Close();
//write each element of buffer as a line in a temporary file
File.WriteAllLines("temp", buffer);
//open that temporary file
myEdit.Load("temp");
}
}
Merge Button Code:
private void merge_Click(object sender, RoutedEventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
ofd.CheckFileExists = true;
if (ofd.ShowDialog() ?? false)
{
string text;
// Read the file and display it line by line.
System.IO.StreamReader file =
new System.IO.StreamReader(ofd.FileName);
while ((text = file.ReadLine()) != null)
{
buffer.Add(text); // myEdit.AppendText(text);
}
file.Close();
File.WriteAllLines("temp", buffer);
myEdit.Load("temp");
}
}
And when I execute this code, it adds lines in between the last 'file's output:
private void myEdit_TextChanged(object sender, EventArgs e)
{
tCheck.Stop();
tCheck.Start();
}
private void TimerEventProcessor(Object myObject, EventArgs myEventArgs)
{
tCheck.Stop();
Application.Current.Dispatcher.Invoke(new Action(() =>
{
buffer.Clear();
StringBuilder sb = new StringBuilder();
// pulls text from textbox
string bigS = myEdit.Text;
// getText();
for (int i = 0; i < (bigS.Length - 1); i++)
{
if (bigS[i] != '\r' && bigS[i + 1] != '\n')
{
sb.Append(bigS[i]);
}
else
{
buffer.Add(sb.ToString());
sb.Clear();
}
}
}));
}
If you are wondering why I don't use the Split method of a string, it is because I need to open 50+ MB text files and I get an out of memory exception upon using it. I really just want to keep formatting the same when I merge a file.
Wow this is a one line fix.
Original Line of Code:
buffer.Add(sb.ToString());
Changed (Correct) Line of Code:
buffer.Add(sb.ToString().Trim());
The changed worked, however if someone has any idea where these extra lines are coming from that would be helpful.
I set up the font manually for the labels, however, when I am saving it as a Word Document the font which I set up previously disappears. I do not know how to figure it out
private void button1_Click(object sender, EventArgs e)
{
string text = label1.Text + textBox1.Text + "\r\n\r\n\r\n" +
label2.Text + textBox2.Text + "\r\n\r\n\r\n";
sSaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Microsoft Word| *.doc";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
MessageBox.Show(path);
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(text);
}
}
}
}
StreamWriter (basically) writes a string (of characters) to a file. Word formatting is not that simple. If you want the formatting then it gets more complicated.
See this MSDN article for more info on formatting Word documents. You need an object that can control the document.
I want to read a text file which contains more than one paragraph separated by new lines. How to read every paragraph alone in RichTextBox and how to transfer to the next paragraph by button next and back to the first paragraph by button previous designed in the form. My code
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
Input.Text = Text;
}
}
Use this code.
var text = File.ReadAllText(inputFilePath);
var paragraphs = text .Split('\n');
paragraphs will be an array of strings containing all the paragraphs.
Use String.split() to split it at '\n'.
Afterwards iterate through the array on the Button next.
private string[] paragraphs;
private int index = 0;
private void LoadFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter =
"txt files (*.txt)|*.txt|All files (*.*)|*.*";
dialog.Title = "Select a text file";
dialog.ShowDialog();
if (dialog.FileName != "")
{
System.IO.StreamReader reader = new System.IO.StreamReader(dialog.FileName);
string Text = reader.ReadToEnd();
reader.Close();
this.Input.TextChanged -= new System.EventHandler(this.Input_TextChanged);
Input.Clear();
paragraphs = Text.Split('\n');
index = 0;
Input.Text = paragraphs[index];
}
}
private void Next_Click(object sender, EventArgs e)
{
index++;
Input.Text = paragraphs[index];
}
(I know this might not be the most elegant solution but it should give an idea on what to do.)
i want to read content of file.but these code is not helping.
string[] readText = File.ReadAllLines(path); this line is giving error.
protected void btnRead_Click(object sender, EventArgs e)
{
string path = fileupload1.PostedFile.FileName;
if (!string.IsNullOrEmpty(path))
{
string[] readText = File.ReadAllLines(path);
StringBuilder strbuild = new StringBuilder();
foreach (string s in readText)
{
strbuild.Append(s);
strbuild.AppendLine();
}
textBoxContents.Text = strbuild.ToString();
}
}
The File.ReadAllText function expects the file to exist on the specified location. You haven't saved it on the server and yet you are attempting to read it. If you don't need to save the uploaded file on the server you could read directly from the input stream.
protected void btnRead_Click(object sender, EventArgs e)
{
if (fileupload1.PostedFile != null && fileupload1.PostedFile.ContentLength > 0)
{
using (var reader = new StreamReader(fileupload1.PostedFile.InputStream))
{
textBoxContents.Text = reader.ReadToEnd();
}
}
}
This will work for text files. If you want to parse some other formats such as Word documents you will need a library to do that.
this should work
string[] lines = System.IO.File.ReadAllLines(#"..\asd.txt");
for (i = 0; i < lines.Count; i++)
System.Console.WriteLine("Contents = " + lines[i]);
}