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;
}
}
}
Related
I have opened a .CSV file in RichTextBox.I added every line's first word to CombobBox items. I want to edit this a specific word and then save it back to the File.
This is how i open the file to richTextBox1.
OpenFileDialog ofd = new OpenFileDialog();
ofd.Filter = "Csv files (.csv)|*.csv";
ofd.Title = "Open a file...";
if (ofd.ShowDialog() == DialogResult.OK)
{
StreamReader sr = new StreamReader(ofd.FileName);
richTextBox1.Text = sr.ReadToEnd();
}
Now i want a Button that finds my comboBox1.Text in richTextBox and replace it with txtbox.Text.
My button looks like this:
private void button1_Click(object sender, EventArgs e)
{
using (TextReader reader = new StringReader(richTextBox1.Text))
{
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
}
}
I would add the method to the end of this button that would save back the text from richTextBox to my .CSV file but this replace method doesnt replace anything in my richTextBox.
My .CSV file (in richTextBox) looks like this:
somestring,somenumber,somespecialcharacters;
somestring2,somenumber2,somespecialcharacters2;
It has about 50 lines,and my combobox is filled with the first words of every line like: "somestring" "somestring2".
When i click on somestring (then its my combobox.text) then i write "newstring" to my txtbox.text. When i click my button it should find comboBox.text in richtxt and replace it with my txtbox.text.
Any ideas why it doesnt work?
You wrote:
but this replace method doesnt replace anything in my richTextBox.
This is because strings in C# are immutable? Whatever you do to strings, the original string is never changed. The result is always in a new string.
See Why .NET String is immutable?
So although your code changes the value of str, the original str that your richtextbox displays is not changed.
string str = reader.ReadToEnd();
string cbtxt = comboBox1.Text;
string tbtxt = txtbox.Text;
str = str.Replace(cbtxt, tbtxt);
str refers to a new string. RichTextBox1.Text still refers to the original string.
Solution: Assign the new string to the rich text box:
this.RichTextBox1.Text = str;
If you want to save the text in a file you'll have to create a FileWriter that will write the new string (not the changed string, strings can't change!).
Depending on how important it is that you don't lose the old file in case of problems, consider using a tmpfile to write, delete the original and move the tmpfile
In order to replace or delete something using a stream reader, you will need to delete every line and replace it with a new (temporary) file.
var tempFile = Path.GetTempFileName(); //Creates temporary file
List<string> linesToKeep = new List<string>(); //Creates list of all the lines you want to keep (everything but your selection)
using (FileStream fs = new FileStream(path(), FileMode.Open, FileAccess.Read)) //(this opens a new filestream (insert your path to your file there)
{
using (StreamReader sr = new StreamReader(fs)) //here is starts reading your file line by line.
{
while (!sr.EndOfStream) //as long it has not finished reading
{
string currentline = sr.ReadLine().ToString(); //this takes the current line it has been reading
string splitline = currentline; //this is a temporary string because you are going to have to split the lines (i think you have 3 so split in "," and then index the first line (your identifier or name)))
if (splitline.Split(';')[0] != ID) //split the line and add your personal identifier so it knows what to keep and what to delete.
{
linesToKeep.Add(currentline); //adds the line to the temporary file list of line that you want to keep
}
}
}
}
File.WriteAllLines(tempFile, linesToKeep); //writes all the lines you want to keep back into a file
File.Delete(path()); //deletes the old file
File.Move(tempFile, path()); //moves temporary file to old location of the old file.
On second notice, check out this code:
private void btnLoad_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.LoadFile(ofd.FileName);
}
}
private void btnSave_Click(object sender, EventArgs e)
{
OpenFileDialog ofd = new OpenFileDialog();
if (ofd.ShowDialog() == DialogResult.OK)
{
richTextBox1.SaveFile(ofd.FileName);
}
}
I think this is more in line with what you had in mind?
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.
I have tried using:
StreamWriter.WriteLine()
StreamWriter.Write()
File.WriteAllText()
But all of those methods write the textbox text to the file without keeping newlines and such chars. How can I go about doing this?
EDIT:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
File.WriteAllText(s.FileName, richTextBox1.Text);
}
}
I am using a multiline RichTextBox to do this.
To expand on tzortzik's answer, if you use StreamWriter and simply access the RichTextBox's Lines property, it will do the work for you:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog s = new SaveFileDialog();
s.FileName = "new_doc.txt";
s.Filter = "Text File | *.txt";
if (s.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(s.FileName))
{
foreach (string line in richTextBox1.Lines)
{
sw.WriteLine(line);
}
}
}
}
Maybe this would help. Is from StreamWriter class documentation.
string[] str = String.Split(...);
// Write each directory name to a file.
using (StreamWriter sw = new StreamWriter("CDriveDirs.txt"))
{
foreach (DirectoryInfo dir in cDirs)
{
sw.WriteLine(dir.Name);
}
}
The idea is to get the text from your textbox and then split it after \n char. The result will be an array of strings, each element containing one line.
Later edit:
The problem is that return carriage is missing. If you look with debugger at the code, you will see that your string has only \n at a new line instead of \r\n. If you put this line of code in you function, you will get the results you want:
string tbval = richTextBox1.Text;
tbval = tbval.Replace("\n", "\r\n");
There should be other solutions for this issue, looking better than this but this one has quick results.
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]);
}
i want to display text from textfile in text box . how can i do this .. in C#
Actually i m making text to speech converter in C# .. SO i want to open text file and want show text of that file in my textbox ..
here is my code
private void button2_Click(object sender, EventArgs e)
{
OpenFileDialog O = new OpenFileDialog();
O.ShowDialog();
Loadfile(O.FileName);
}
private void Loadfile(string filename)
{
TextRange range;
FileStream fStream;
if (File.Exists(fileName))
{
range = new TextRange(textBox1.Text.TrimStart, textBox1.Text.TrimEnd);
fStream = new FileStream(filename, FileMode.Open);
range.Load(fStream, DataFormats.Text);
fStream.Close();
}
}
i got error in textBox1.Text.TrimStart, textBox1.Text.TrimEnd .. i dont want to use Richtextbox because .. for that i have to use . Document property of richtextbox cz 4 tht i bound to use WPF ...
(richTextBox1.Document.ContentStart, richTextBox1.Document.ContentEnd)
Please Help me on this
Cheers !
Wahib Idris
Any help will be appreciated .. Thanx in advance
Please Help
This should work:
private void Loadfile(string filename)
{
if (File.Exists(fileName))
{
textBox1.Text = File.ReadAllText(filename);
}
}
var fileText = File.ReadAllText(filePath);
textBox.Text = fileText;
You can load content of file to string simply this way:
private string Loadfile(string filePath)
{
string text = String.Empty;
if (File.Exists(filePath))
{
StreamReader streamReader = new StreamReader(filePath);
text = streamReader.ReadToEnd();
streamReader.Close();
}
return text;
}
The easiest way:
if (File.Exists(filePathString))
yourTextBox.Text = File.ReadAllText(filePathString);