Stream read selected listbox item query - c#

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;

Related

Large strings added to a text box freezing my program

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.

C# Out of Range: Spawning textFile contents to listBoxes

I am creating an application would take textfile paths from a textfile, and then load them into a listbox, which when clicked on in listbox, the textfile content will spawn in a script editor widget called textEditorControl1.
The thing is. When I delete a thing from the listbox which hosts the textfile names, AND THEN, click on another item in listbox; it gives me an error:
An unhandled exception of type 'System.ArgumentOutOfRangeException'
occurred in mscorlib.dll
Additional information: Index was out of range. Must be non-negative
and less than the size of the collection.
on string fullFileName2 = selectedScripts[listBox3.SelectedIndex];
List<String> fullFileName;
List<String> fullFileName2;
List<string> selectedScripts = new List<string>();
public void listBox3_SelectedIndexChanged(object sender, EventArgs e)
{
if (listBox3.SelectedIndex >= 0)
{
string fullFileName2 = selectedScripts[listBox3.SelectedIndex];
textBox3.Text = fullFileName2;
string File1 = fullFileName2;
string text = System.IO.File.ReadAllText(File1);
textEditorControl1.Text = text;
textEditorControl1.Refresh();
}
else
{
}
private void materialFlatButton10_Click(object sender, EventArgs e)
{
OpenFileDialog OpenFileDialog1 = new OpenFileDialog();
OpenFileDialog1.Multiselect = true;
OpenFileDialog1.Filter = "Text Files|*.txt|All Files|*.*|Lua Files|*.lua";
OpenFileDialog1.Title = "Select a Text/Lua File";
if (OpenFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
fullFileName2 = new List<String>(OpenFileDialog1.FileNames);
foreach (string s in OpenFileDialog1.FileNames)
{
listBox3.Items.Add(Path.GetFileName(s));
selectedScripts.Add(s);
}
}
}
private void deleteFromListToolStripMenuItem_Click(object sender, EventArgs e)
{
label4.Text = " ";
textBox3.Text = "";
IDocument document = textEditorControl1.Document;
document.Remove(0, document.TextLength);
textEditorControl1.Refresh();
selectedScripts.Clear();
for (int i = listBox3.SelectedIndices.Count - 1; i >= 0; i--)
{
listBox3.Items.RemoveAt(listBox3.SelectedIndices[i]);
}
}
You're clearing SelectedScripts, and then when you click on something, you're trying to access an item in SelectedScripts at index listBox3.SelectedIndex, but at this point SelectedScripts is empty.
I think your delete method should be this:
private void deleteFromListToolStripMenuItem_Click(object sender, EventArgs e)
{
label4.Text = " ";
textBox3.Text = "";
IDocument document = textEditorControl1.Document;
document.Remove(0, document.TextLength);
textEditorControl1.Refresh();
for (int i = listBox3.SelectedIndices.Count - 1; i >= 0; i--)
{
selectedScripts.RemoveAt(listBox3.SelectedIndices[i]);
listBox3.Items.RemoveAt(listBox3.SelectedIndices[i]);
}
}
Note that the UI ListBox control can take classes, so you could encapsulate all of your data into one class object which you add to the list.

import/export text to/from listview [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
i am having two problems:
1- when ever i click on open button, it shows me the openfiledialog twice (when i select my file and click ok, it reopens the selection windows again, only repeats it once).
2- i am trying to export and import text files from a list view, so far i managed to export a text file from the list view, but i failed at importing it back in.
here is my code (for both situations since it's the same project):
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
string path;
//string fname;
private void abtmenuItem10_Click(object sender, EventArgs e)
{
MessageBox.Show("DB Kai UB Text Extractor\n by Omarrrio 2012", "About...", MessageBoxButtons.OK, MessageBoxIcon.Information, MessageBoxDefaultButton.Button1, 0, "http://gbatemp.net/user/245642-omarrrio/");
}
private void exitmenuItem4_Click(object sender, EventArgs e)
{
this.Close();
}
private void sbtmenuItem5_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Sbt File";
ofd.Filter = "Sbt Files (*.sbt)|*.sbt|All Files (*.*)|*.*";
//if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
}
private void msgmenuItem6_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
pntrsmenuItem4.Text = "Number of Pointer = ";
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Open Msg File";
ofd.InitialDirectory = Application.StartupPath;
ofd.Filter = "Msg Files (*.msg)|*.msg|All Files (*.*)|*.*";
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.Cancel)
return;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
path = ofd.FileName;
BinaryReader br = new BinaryReader(File.OpenRead(path), Encoding.GetEncoding("Shift_JIS"));
br.BaseStream.Position = 0x4;
int num_pointers = br.ReadInt16();
if (num_pointers == 0x56C)
{
MessageBox.Show("This File is not supported as it's pointer system is somehow F*cked up, please use another file, thank you.","Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
return;
}
else
{
MessageBox.Show("File opened Succesfully!", "Info", MessageBoxButtons.OK, MessageBoxIcon.Information);
pntrsmenuItem4.Visible = true;
pntrsmenuItem4.Text += num_pointers.ToString();
List<int> offsets = new List<int>();
for (int i = 2; i <= (num_pointers * 2); i += 2)
{
br.BaseStream.Position = i * 4 + 4;
offsets.Add(br.ReadInt32());
//listView1.Items.Add(br.ReadUInt32().ToString("X"));
}
Dictionary<int, string> values = new Dictionary<int, string>();
for (int i = 0; i < offsets.Count; i++)
{
int currentOffset = offsets[i];
int nextOffset = (i + 1) < offsets.Count ? offsets[i + 1] : (int)br.BaseStream.Length;
int stringLength = (nextOffset - currentOffset - 1) / 2;
br.BaseStream.Position = currentOffset;
var chars = br.ReadChars(stringLength);
values.Add(currentOffset, new String(chars));
}
foreach (int offset in offsets)
{
listView1.Items.Add(offset.ToString("X")).SubItems.Add(values[offset]);
}
br.Close();
br = null;
}
}
ofd.Dispose();
ofd = null;
}
private void EtxtmenuItem8_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Title = "Save Text File";
sfd.DefaultExt = ".txt";
sfd.InitialDirectory = Application.StartupPath;
sfd.Filter = "Text Files (*.txt)|*.txt";
DialogResult result = sfd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamWriter wwrite = new StreamWriter(sfd.FileName, false, Encoding.Unicode);
for (int i = 0; i < listView1.Items.Count; ++i)
{
string name = listView1.Items[i].SubItems[1].Text;
wwrite.WriteLine("-" + name);
}
wwrite.Close();
}
private void ItxtmenuItem4_Click(object sender, EventArgs e)
{
OpenFileDialog ifd = new OpenFileDialog();
ifd.Title = "Open Text File";
ifd.Filter = "Text Files (*.txt)|*.txt";
ifd.InitialDirectory = Application.StartupPath;
DialogResult result = ifd.ShowDialog();
if (result == DialogResult.Cancel)
return;
StreamReader sr = new StreamReader(ifd.FileName);
int aa = 0;
while (sr.Peek() >= 0)
{
string[] a2 = sr.ReadLine().Split('-');
if (a2.Length == 2)
{
aa = int.Parse(a2[0].ToString());
listView1.Items[aa].SubItems[1].Text = a2[1].Replace("~", "\n");
}
else
{
listView1.Items[aa].SubItems[1].Text += "\n" + a2[0];
}
}
sr.Close();
}
}
It's a bit hard to see which Menu click corresponds to which method here, but I'll I'm guessing that the offending piece of code is msgmenuItem6_Click.
The reason that the Dialog is showing up twice is because you call ShowDialog twice.
DialogResult result = ofd.ShowDialog();
if (result == DialogResult.Cancel)
return;
if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
You should be doing
if (result == System.Windows.Forms.DialogResult.OK)
Regarding why you aren't able to read your file. Are you certain that there is data in the while you're trying to read? To ensure that you are opening it correctly, you can also try File.ReadAllText and make sure that it's being read in correctly.

to display doc file in text format asp.net c#

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]);
}

how to save data loaded from external file into the program?

Based on the function below, it is used to load data from file .dat. The problem is every time i load a new file, the previous file will be overwritten. how to store the data from previous file inside the program so that when loading a new file, the new data will be added to the previous one?
private void btnLoad_Click(object sender, EventArgs e)
{
try
{
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "Data File (*.dat)|*.dat";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
TextReader f = new StreamReader(openFileDialog1.FileName);
String line;
this.letterData.Clear();
this.letters.Items.Clear();
while ((line = f.ReadLine()) != null)
{
int sampleSize = Form1.DOWNSAMPLE_HEIGHT * Form1.DOWNSAMPLE_WIDTH;
char ch = char.ToUpper(line[0]);
bool[] sample = new bool[sampleSize];
int idx = 2;
for (int i = 0; i < sampleSize; i++)
{
if (line[idx++] == '1')
sample[i] = true;
else
sample[i] = false;
}
this.letterData.Add(ch, sample);
this.letters.Items.Add("" + ch);
}
f.Close();
}
MessageBox.Show(this, "File Loaded");
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message);
}
}
Remove the following lines?
this.letterData.Clear();
this.letters.Items.Clear();
EDIT:
Or change to te following in order to have unique keys in your dictionary
this.letterData.Add(string.Format("{0}_{1}", openFileDialog1.FileName, ch), sample);
this.letters.Items.Add(ch.toString());

Categories