This program opens files into a textbox. It works fine with small files such as 4KB in size, but I am having trouble with a 200KB file. Ideally, I want to be able to open files of any size, but opening large files into a text box freezes the program. What am I doing wrong?
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if(openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
textBox1.Text = String.Empty;
while (!sr.EndOfStream)
{
textBox1.Text += sr.ReadLine() + Environment.NewLine;
}
sr.Close();
}
openFileDialog1.Dispose();
}
Reading file line-by-line gives unwanted overhead. It would be better to read all file at once.
Consider to use async/await. This will bring you more responsive interface.
So I would suggest the next solution:
private async void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
textBox1.Text = await sr.ReadToEndAsync();
sr.Close();
}
openFileDialog1.Dispose();
}
Edit
As discussed in the comments, this solution doesn't correctly process unix-style line breaks. For this case it can be other decision:
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFileDialog1.FileName);
Text = openFileDialog1.FileName + " - " + "Fixprt";
var sb = new StringBuilder();
while (!sr.EndOfStream)
{
sb.AppendLine(sr.ReadLine());
}
textBox1.Text = sb.ToString();
sr.Close();
}
openFileDialog1.Dispose();
}
Now we are using StringBuilder, which is designed for fast processing of string data.
Related
I tried to do a form application and I have a problem about use StreamReader feature. in StreamWriter feature, I did it but StreamReader just read the last line and The txt file contains, in many rows for example: names and phone numbers but like I said the code read last line
private void button2_Click(object sender, EventArgs e)
{
//1
StreamWriter sw;
sw = File.AppendText("metinbelgesi.txt");
sw.Write(textBox1.Text + " ");
sw.Write(textBox2.Text + " ");
sw.WriteLine(textBox3.Text+"." );
sw.Flush();
sw.Close();
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
FileStream fs = new FileStream("metinbelgesi.txt", FileMode.Open, FileAccess.Read);
StreamReader sw = new StreamReader(fs);
//sw = File.AppendText("metinbelgesi.txt");
string yazi = sw.ReadLine();
while (yazi != null)
{
richTextBox1.Text = yazi;
}
sw.Close();
fs.Close();
}
else
{
MessageBox.Show("First, You Join.");
}
}
What do I do?
You are reading it line by line and keep overwriting richTextBox1 with the next line... try:
richTextBox1.Text = "";
while (yazi != null)
{
richTextBox1.Text += yazi;
yazi = sw.ReadLine();
}
Or, if you don't need to parse each line, you can read it all in one go:
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
According to your code, you're only reading the first line. There should be a ReadLine() statement inside your loop as well.
Pay attention that you will always overwrite the contents of the textbox with the line of text you've just read.
So, when you've finished your loop, only the last line that you've read will occur in the textbox.
For simplicity, you can also have a look at the File class and more specifically the ReadAllLines() method.
You should probaby try to make your life easier by using some of the simpler File operations.
Try this instead:
private void button2_Click(object sender, EventArgs e)
{
File.AppendAllText("metinbelgesi.txt", $"{textBox1.Text} {textBox2.Text} {textBox3.Text}.");
}
private void button3_Click(object sender, EventArgs e)
{
if (File.Exists("metinbelgesi.txt"))
{
richTextBox1.Text = File.ReadAllText("metinbelgesi.txt");
}
else
{
MessageBox.Show("First, You Join.");
}
}
i need to write app to remove specific text line in very large XML file (about 3,5 GB).
I wrote this code:
string directoryPath;
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
ofd.Filter = "XML|*.xml";
if (ofd.ShowDialog() == DialogResult.OK)
{
directoryPath = Path.GetDirectoryName(ofd.FileName);
textBox2.Text = directoryPath;
textBox1.Text = ofd.SafeFileName;
}
}
private void Replace()
{
StreamReader readerFile = new StreamReader(ofd.FileName, System.Text.Encoding.UTF8);
while (!readerFile.EndOfStream)
{
string stringReplaced;
string replaceResult = textBox2.Text + "\\" + "replace_results";
Directory.CreateDirectory(replaceResult);
StreamWriter writerFile = new StreamWriter(replaceResult + "\\" + textBox1.Text, true);
StringBuilder sb = new StringBuilder();
char[] buff = new char[10 * 1024 * 1024];
int xx = readerFile.ReadBlock(buff, 0, buff.Length);
sb.Append(buff);
stringReplaced = sb.ToString();
stringReplaced = stringReplaced.Replace("line to remove", string.Empty);
writerFile.WriteLine(stringReplaced);
writerFile.Close();
writerFile.Dispose();
stringReplaced = null;
sb = null;
}
readerFile.Close();
readerFile.Dispose();
}
private void button2_Click(object sender, EventArgs e)
{
if (!backgroundWorker1.IsBusy)
{
backgroundWorker1.RunWorkerAsync();
toolStripStatusLabel1.Text = "Replacing in progress...";
}
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
try
{
Replace();
toolStripStatusLabel1.Text = "Replacing complete!";
}
catch
{
toolStripStatusLabel1.Text = "Error! Replacing aborted!";
}
}
}
it works, but not as well because new file (after remove lines) is bigger than original file and at the end of new file are added some junk (lots of dots), screenshot:
https://images81.fotosik.pl/615/873833aa0e23b36f.jpg
How i can fix my code to make new file the same as old file, only without specific lines?
For a start why keep opening and closing the output file? Keep it open.
Secondly reading blocks – which could lead to "line to remove" being split across blocks – and writing lines is an odd mix.
But I expect your issue is three fold:
You do not set the encoding of the output file.
When you read the buffer (10MB) you may get fewer characters read – the return from ReadBlock. But you always write the complete block. Limit the write to match the amount read (as updated but the replace).
ReadBlock will include end of lines, but WriteLine will add them: either work on blocks or on lines. Mixing will only create problems (and avoid the second issue above).
This leads to code something like:
using (var rdr = OpenReadFile(...))
using (var wtr = OpenWriteFile(...)) {
string line;
while ((line = rdr.ReadLine()) != null) {
line = line.Replace(x, y);
str.WriteLine(line);
}
}
NB Processing XML as text could lead to corrupting the XML (there is no such thing as "invalid XML": either the document is valid XML or it isn't XML, just something that looks a bit like it might be XML). Therefore any such approach needs to be handled with caution. The "proper" answer is to process as XML with the streaming APIs (XmlReader and XmlWriter) to avoid parsing the whole document as one.
I trying do this by XmlTextReader but i have system.xml.xmlexception during read my file, screenshot: https://images82.fotosik.pl/622/d98b35587b0befa4.jpg
Code:
XmlTextReader xmlReader = new XmlTextReader(ofd.FileName);
XmlDocument doc = new XmlDocument();
doc.Load(xmlReader);
I'm trying to remove out-of-sequence white spaces from a text file to one-space sequence in a winForm i.e.,
From
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
To
sagchjvcsj kbschjsdchs sudbjsdbl
sdvbchjbvsdjc kbsadcsadk kskbjdsdcksajdbc
My implementation is:
private void buttonBrowse_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialogImage = new OpenFileDialog();
openFileDialogImage.Filter = "Text files | .txt";
openFileDialogImage.Multiselect = false;
if (openFileDialogImage.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialogImage.OpenFile()) != null)
{
textBoxFileName.Text = openFileDialogImage.FileName;
}
}
}
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
using (StreamReader reader = new StreamReader(path, true))
{
s = reader.ReadToEnd();
}
string[] parts = s.Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
File.CreateText(pathSave);
using (StreamWriter sw = new StreamWriter(pathSave))
{
sw.Write(parts);
}
}
}
}
Error that I am getting on line using (StreamWriter sw = new StreamWriter(pathSave)) is:
The process cannot access the file 'E:\test.txt' because it is being used by another process.
I downloaded ProcessWorker to see which process is currently locking Test.txt but I don't see any process using it. Any ideas on how to solve it?
In addition to the other suggestions, your problem is that File.CreateText() will lock so you need to release the lock. I have wrapped the call to File.CreateText() in a using statement to release the lock.
There was an issue with the output of the StreamWriter so I made some changes to get the expected output as per your question.
private void buttonGo_Click(object sender, EventArgs e)
{
string path = textBoxFileName.Text;
string s = string.Empty;
string[] parts;
using (StreamReader reader = new StreamReader(path, true))
{
parts = reader.ReadToEnd().Split(new[] { ' ' }, StringSplitOptions.RemoveEmptyEntries);
}
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.ShowDialog();
string pathSave = saveFileDialog.FileName;
using (File.CreateText(pathSave))
{ }
using (StreamWriter sw = new StreamWriter(pathSave))
{
string result = string.Empty;
foreach (string s in parts)
{
result += s + " ";
}
sw.Write(result);
}
}
I have an app that reads a directory, gets a list of the files (segy) and populates a listbox on the left side of the app with the filenames. Upon clicking an item in the listox I'd like the rich text box on the right to display the content of the file.
I have the app working if I use the openfiledialog to select one of the files in the directory, I'm having issues trying to get the stream reader to read the selected file I've clicked.
The working simple openfiledialog code below.
openFileDialog1.Filter = "All Files|*.*";
openFileDialog1.Title = "Open SEG-Y Files";
DialogResult result = openFileDialog1.ShowDialog();
StreamReader readFile = new StreamReader(openFileDialog1.FileName, ebcdic);
readFile.BaseStream.Seek(0, SeekOrigin.Begin);
readFile.Read(data, 0, 3200);
string stringData = "";
for (int i = 0; i < data.Length; i++)
{
if ((i % 80) == 0 && stringData != "")
stringData += Environment.NewLine;
stringData += data[i].ToString();
}
rtbHeader.Text = stringData;
rtb.AppendText(value);
rtb.AppendText(System.Environment.NewLine);
My code
private void txtUpdate(string value)
{
lstFiles.Items.Add(value + Environment.NewLine);
lstFiles.TopIndex = lstFiles.Items.Count - 1;
lstFiles.Update();
}
private void btnFolder_Click(object sender, EventArgs e)
{
txtPath.Text = "";
lstFiles.Items.Clear();
rtbHeader.Clear();
DialogResult result = folderBrowserDialog1.ShowDialog();
if (result == DialogResult.OK)
{
txtPath.Text = folderBrowserDialog1.SelectedPath;
}
}
private void btnFiles_Click(object sender, EventArgs e)
{
lstFiles.Items.Clear();
string path = txtPath.Text;
List<string> files = new List<string>(Directory.EnumerateFiles(txtPath.Text, "*.sgy", SearchOption.AllDirectories).Select(Path.GetFileName).OrderBy(x => x));
if (files == null || files.All(x => string.IsNullOrWhiteSpace(x)))
{
MessageBox.Show("There are no files with extension" + " sgy", "Error", MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
return;
}
foreach (string file in files)
{
this.Invoke(new Action(() => txtUpdate(file)));
}
}
private void lstFiles_MouseClick(object sender, MouseEventArgs e)
{
rtbHeader.Clear();
String item = (Convert.ToString(lstFiles.SelectedItem));
//MessageBox.Show(item);
StreamReader readFile = new StreamReader(item, ebcdic);
readFile.BaseStream.Seek(0, SeekOrigin.Begin);
readFile.Read(data, 0, 3200);
string stringData = "";
for (int i = 0; i < data.Length; i++)
{
if ((i % 80) == 0 && stringData != "")
stringData += Environment.NewLine;
stringData += data[i].ToString();
}
rtbHeader.Text = stringData;
}
}
Im getting an Illegal characters in path exception on this bit.
StreamReader readFile = new StreamReader(item, ebcdic);
Thanks
The code example really should be simpler. Much simpler. And the problem description more specific. Much more specific. See https://stackoverflow.com/help/mcve and https://stackoverflow.com/help/how-to-ask
That said, I believe that if you change this statement in the txtUpdate() method:
lstFiles.Items.Add(value + Environment.NewLine);
to this:
lstFiles.Items.Add(value);
It will work. The exception is most likely caused by the fact that you have newline characters in your strings. Not only does that make the filename not the one you want, it's not a valid character in Windows paths.
Also note that the items in the ListBox you've added are already strings. You don't need to call Convert.ToString() on them. You can just cast them back to a string:
String item = (string)lstFiles.SelectedItem;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Prototype
{
public partial class Form1 : Form
{
object oDocument;
Microsoft.Office.Interop.Word._Application wordApp;
Microsoft.Office.Interop.Word._Document doc;
public Form1()
{
InitializeComponent();
}
private void button9_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Office Documents " + " " + "(*.doc, *.docx)|*.doc;*.docx";
openFileDialog1.FilterIndex = 1;
System.Windows.Forms.HtmlDocument document;
string sFileName;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
sFileName = openFileDialog1.FileName;
if (sFileName.Length != 0)
{
oDocument = null;
webBrowser1.Navigate(sFileName);
document = webBrowser1.Document;
wordApp = webBrowser1.Document;
}
}
private void Form1_Load(object sender, EventArgs e)
{
/*
if (sender.Equals(button9))
{
openFileDialog1.Filter = "Office Documents " + " " + "(*.doc, *.docx)|*.doc;*.docx";
}
else
openFileDialog1.Filter = "Office Documents " + " " + "(*.doc, *.docx, *.xls, *.pptx, *.pdf, *.odt)|*.doc;*.docx;*.xls;*.pptx;*.pdf;*.odt"; ;
openFileDialog1.FilterIndex = 1;
*/
}
private void webBrowser1_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
{
oDocument = webBrowser1.Document;
}
private void button8_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Office Documents " + " " + "(*.xls, *.xlsx)|*.xls;*.xlsx";
openFileDialog1.FilterIndex = 1;
System.Windows.Forms.HtmlDocument document;
string sFileName;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
sFileName = openFileDialog1.FileName;
if (sFileName.Length != 0)
{
oDocument = null;
webBrowser1.Navigate(sFileName);
document = webBrowser1.Document;
}
}
private void button7_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Office Documents " + " " + "(*.ppt, *.pptx)|*.ppt;*.pptx";
openFileDialog1.FilterIndex = 1;
System.Windows.Forms.HtmlDocument document;
string sFileName;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
sFileName = openFileDialog1.FileName;
if (sFileName.Length != 0)
{
oDocument = null;
webBrowser1.Navigate(sFileName);
document = webBrowser1.Document;
}
}
private void button10_Click(object sender, EventArgs e)
{
openFileDialog1.Filter = "Office Documents " + " " + "(*.pdf)|*.pdf";
openFileDialog1.FilterIndex = 1;
System.Windows.Forms.HtmlDocument document;
string sFileName;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
sFileName = openFileDialog1.FileName;
if (sFileName.Length != 0)
{
oDocument = null;
webBrowser1.Navigate(sFileName);
document = webBrowser1.Document;
}
}
}
}
My code uses a web browser to display a word, excel, and powerpoint. Unfortunately every time it tries to open it, an alert box first appears and asks if i want to save or open or cancel. How am i suppose to remove it?
You are running into browser security. You can't just have documents that may contain malicious items in them open without user input.
Also... you need to refactor your code. There is so much code that you have that is the exact same.
private string GetFileFromUser(string aFilter){
openFileDialog1.Filter = aFilter
openFileDialog1.FilterIndex = 1;
System.Windows.Forms.HtmlDocument document;
openFileDialog1.FileName = "";
openFileDialog1.ShowDialog();
return openFileDialog1.FileName;
}
fileName = GetFileFromUser("Office Documents (*.xls, *.xlsx)|*.xls;*.xlsx");
The way your doing it, the alert box will always show up unless you change your security settings in Internet Explorer. This is not advised and not even fesible if you are distributing to clients.
The better way to do this is to use WebRequest and WebResponse to get the source of the HTML page. Then you should parse out the URL to the Word or Excel Document, then use can use WebRequest and WebResponse again to open the document and save it. From there you can use WebBrowser control to populate the Document property with the word or excel document.