to display doc file in text format asp.net c# - 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]);
}

Related

Read text file, split it, then show it in listBox

I need to read a text file containing time stamps and temperatures. The thing is, I need to only show the temperatures in a listBox, spliting the string before displaying it.
So far I've managed to show the text file in the list, but im struggling with removing the timestamps.
My code:
public partial class Form1 : Form
{
OpenFileDialog openFile = new OpenFileDialog();
string line = "";
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(openFile.FileName);
while(line != null)
{
line = sr.ReadLine();
if(line != null)
{
string[] newLine = line.Split(' ');
listBox1.Items.Add(newLine);
}
}
sr.Close();
}
}
Now the listBox only shows String[] array.
Oh, and also I need to include this in my code:
const int numOfTemp = 50;
double dailyTemp[numOfTemps];
The textfile is in this format:
11:11:11 -10,50
You should take [1] item of the the array after Split:
using System.Linq;
...
private void button1_Click(object sender, EventArgs e)
{
if (openFile.ShowDialog() != DialogResult.OK)
return;
var temps = File
.ReadLines(openFile.FileName)
.Select(line => line.Split(' ')[1]); // we need temperature only
try {
listBox1.BeginUpdate();
// In case you want to clear previous items
// listBox1.Items.Clear();
foreach (string temp in temps)
listBox1.Items.Add(temp);
}
finally {
listBox1.EndUpdate();
}
}

How to get a richTextBox to read listbox

what i'm trying to do is this i have a listBox that shows all .txt files in a folder but I want to be able to click a .txt in the listBox and have my richTextBox show the text from that .txt file.
Code to show files:
private void Scripts_Load(object sender, EventArgs e)
{
DirectoryInfo dinfo = new DirectoryInfo(#"scripts");
FileInfo[] Files = dinfo.GetFiles("*.txt");
foreach (FileInfo file in Files)
list.Items.Add(file.Name);
}
As for the code to show in textBox I have tried many internet answers and got nowhere main errors being Argument 1: cannot convert from 'object' to 'string'
The closest I have got is with this
//Get the FileInfo from the ListBox Selected Item
FileInfo SelectedFileInfo = (FileInfo) listBox.SelectedItem;
//Open a stream to read the file
StreamReader FileRead = new StreamReader(SelectedFileInfo.FullName);
//Read the file to a string
string FileBuffer = FileRead.ReadToEnd();
//set the rich text boxes text to be the file
richTextBox.Text = FileBuffer;
//Close the stream so the file becomes free!
FileRead.Close();
It Crashes saying: `System.InvalidCastException: 'Unable to cast object of type 'System.String' to type 'System.IO.FileInfo'.'
There was already a comment saying that this happens and the guy replied saying change line 1 to FileInfo SelectedFileInfo = new FileInfo(listBox1.SelectedItem); this failed sayingArgument 1: cannot convert from 'object' to 'string'
`
I did it YAY!!!
private async void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = list.SelectedItem.ToString();
richTextBox1.Text = value1;
using (StreamReader sr = new StreamReader("scripts\\" + value1))
{
{
String line = await sr.ReadToEndAsync();
richTextBox1.Text = line;
}
}
}
The reason is that in your Listbox are strings stored.
You musst try to convert them.
var filename as listBox.SelectedItem as string;
if(string.IsNullOrWhiteSpace(filename))
{
return;
}
var path = Path.Combine(#"C:\", filename);
var fileinfo = new FileInfo(path);
I did it, it took me some time but I realized that I could get the text and move it to the textbox I didn't think that would help because I wanted the document not the name but then I put the Var as the file path, Here:
private async void listBox1_SelectedIndexChanged(object sender, EventArgs e)
{
string value1 = list.SelectedItem.ToString();
richTextBox1.Text = value1;
using (StreamReader sr = new StreamReader("scripts\\" + value1))
{
{
String line = await sr.ReadToEndAsync();
richTextBox1.Text = line;
}
}
}

How to save content from List<string> to a text file in C#?

I have a listbox that displays the names of the files that are opened either with a dragDrop functionality or with an OpenFileDialog, the file paths are stored in the List named playlist, and the listbox only displays the names without paths and extensions. When my form closes, the playlist content is saved to a .txt file. When I open again my application, the content in the text file is stored again in the listbox and the playlist. But when I add new files after re-opening the form, I don't know why it leaves a blank line between the last files and the recently added ones.
This is the code I use to WRITE the content of playlist(List) in the txt file:
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
if(listBox1.Items.Count > 0)
{
StreamWriter str = new StreamWriter(Application.StartupPath + "/Text.txt");
foreach (String s in playlist)
{
str.WriteLine(s);
}
str.Close();
}
This is the code used to READ the same txt file:
private void Form1_Load(object sender, EventArgs e) //Form Load!!!
{
FileInfo info = new FileInfo(Application.StartupPath + "/Text.txt");
if(info.Exists)
{
if (info.Length > 0)
{
System.IO.StreamReader reader = new System.IO.StreamReader(Application.StartupPath + "/Text.txt"); //StreamREADER
try
{
do
{
string currentRead = reader.ReadLine();
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
} while (true);
}
catch (Exception)
{
reader.Close();
listBox1.SelectedIndex = 0;
}
}
else
{
File.Delete(Application.StartupPath + "/Text.txt");
}
}
else
{
return;
}
}
The code used to add files to listbox and playlist:
OpenFileDialog ofd = new OpenFileDialog();
ofd.Title = "Select File(s)";
ofd.Filter = "Audio Files (*.mp3, *.wav, *.wma)|*.mp3|*.wav|*.wma";
ofd.InitialDirectory = "C:/";
ofd.RestoreDirectory = false;
ofd.Multiselect = true;
ofd.ShowDialog();
foreach (string s in ofd.FileNames)
{
listBox1.Items.Add(Path.GetFileNameWithoutExtension(s));
playlist.Add(s);
}
listBox1.SelectedIndex = 0;
This is what I get when I add new files after re-opening my form:
Thanks in advance, I hope StackOverflow community can help me!
First of all: debug your code and you'll find the problem yourself :)
Issue is the use of the WriteLine method. The last line you write should use the Write method instead so that you don't have an empty line at the end. Alternatively and easier to implement is to only add non-empty lines to your playlist such like this:
// ...
do
{
string currentRead = reader.ReadLine();
if (!string.IsNullOrWhiteSpace(currentRead)) // ignore empty lines
{
playlist.Add(currentRead);
listBox1.Items.Add(System.IO.Path.GetFileNameWithoutExtension(currentRead));
}
} while (true);
As a side comment: while (true) and using exception handling is a bad approach to end a loop.

Stream read selected listbox item query

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;

How can I save a list to a file then read the items back into a ListBox?

I am attempting to save a simple list to a file without using Serialize. Is this possible?
public partial class Form1 : Form
{
public List<string> _testList = new List<string>();
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
int _add = 0;
string _addString ="";
for (int i = 0; i < 5; i++)
{
_add =+ i;
_addString = Convert.ToString(_add);
_testList.Add(_addString);
}
TextWriter tw = new StreamWriter("SavedList.txt", true);
foreach (string s in _testList)
tw.WriteLine(s);
tw.Close();
StreamReader streamReader = new StreamReader("SavedList.txt");
// Read the data to the end of the stream.
listBox1.Text = streamReader.ReadToEnd();
// Close the text stream reader.
streamReader.Close();
// Close the file stream.
//fileStream.Close();
}
private void button2_Click(object sender, EventArgs e)
{
Close();
}
}
This emits no errors, however it does nothing.
I will use Serialize if necessary, however the suspicion is that is not necessary. Is it?
You can use the File Class to facilitate this.
File.WriteAllLines("SavedList.txt", _testList.ToArray());
To read it back you can then use:
string[] lines = File.ReadAllLines("SavedList.txt");
foreach (string line in lines)
listBox1.Items.Add(line);
your problem is that the Text field of ListBox
doesn't work like that.
change:
listBox1.Text = streamReader.ReadToEnd();
to:
foreach(string s in streamReader.ReadToEnd().Split(new string[]{"\r\n"}))//!!!the end of line characters may differ depending on your system!!!
{
listBox1.Items.Add(s);
}
the Text field holds the currently selected text . it is not for adding items to the list.

Categories