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.)
Related
i want to make a windows forms app with 2 buttons
1 Button to find a .wtf or .txt file
Second Button to write a line into selected file let`s say "example"
this is my first button
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = false;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
string sFileName = choofdlog.FileName;
}
}
now how do i make the second button write "example" into the file i selected with the first one ?
You can achieve this in two steps:
First, you have to store the file name in a member variable:
private string _fileName;
private void button5_Click_1(object sender, EventArgs e)
{
OpenFileDialog choofdlog = new OpenFileDialog();
choofdlog.Filter = "All Files (*.*)|*.*";
choofdlog.FilterIndex = 1;
choofdlog.Multiselect = false;
if (choofdlog.ShowDialog() == DialogResult.OK)
{
_fileName = choofdlog.FileName;
}
}
In the second step, you have to define the logic of button 2:
private void secondButton_Click_1(object sender, EventArgs e)
{
System.IO.File.WriteAllText( _fileName, "Example" );
}
"1 Button to find a .wtf or .txt file"
To look for specific file extensions you should change your filter a bit
openFileDialog.InitialDirectory = "c:\\";
openFileDialog.Filter = "txt files (*.txt)|*.txt|wtf files (*.wtf)|*.wtf";
openFileDialog.FilterIndex = 2;
openFileDialog.RestoreDirectory = true;
Microsoft docs
so I am writing a c# program which will return a text file selected in a textbox a string[].
But when trying to do this it gets an error saying "a static local function cannot contain a reference to this or base".
Here is the code for collecting the textbox string
string[] words = { File.ReadAllText(dicuploadname.Text)
This is where the error appears. The code for the textbox in question is as follows:
Private void uploaddict_Click(object sender, EventArgs e)
{
OpenFileDialog fdlg = new OpenFileDialog();
MessageBox.Show("The dictionary will need to be a .txt file.");
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.FilterIndex = 2;
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
{
dicuploadname.Text = fdlg.FileName;
}
}
public static void dicuploadname_TextChanged(object sender, EventArgs e)
{
}
public string text = dicuploadname.Text;
}
}
Also included is the code for the browse button that selects the text file and pastes it's location to the textbox.
Not sure how to return the contents of the text file as a string[]? Thanks.
Newest code:
else
{
var myInt = int.Parse(min.Text);
int seconds = myInt * 60000;
System.Timers.Timer aTimer = new System.Timers.Timer();
aTimer.Elapsed += new ElapsedEventHandler(TimerMethod);
aTimer.Interval = seconds;
aTimer.Enabled = true;
// Do something with t...
string uriString = "https://open.spotify.com/search/";
static void TimerMethod(object source, ElapsedEventArgs e)
{
string uriString = "https://open.spotify.com/search/";
WebClient webClient = new WebClient();
Random r = new Random();
string words;
words = File.ReadAllText(dicuploadname.Text);
Console.WriteLine(words[r.Next(0, words.Length)]);
string word = words[r.Next(0, words.Length)];
NameValueCollection nameValueCollection = new NameValueCollection();
nameValueCollection.Add(uriString, word);
webClient.QueryString.Add(nameValueCollection);
var spotifysearch = new ProcessStartInfo
{
FileName = "https://open.spotify.com/search/" + word,
UseShellExecute = true
};
Process.Start(spotifysearch);
}
}
}
private void HiveMind_Click_1(object sender, EventArgs e)
{
var HiveMind= new HiveMind();
HiveMind.Show();
}
private void uploaddict_Click(object sender, EventArgs e)
{
string[] words;
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
words = File.ReadAllText(fdlg.FileName).Split(' ');
}
public string words;
private void dicuploadname_TextChanged(object sender, EventArgs e)
{
}
}
}
Looking at your posted code, dicuploadname is not a variable but a event handler. Change it to this, which assigns the variable words by reading the user specified text file and splitting it on the space character.
private void uploaddict_Click(object sender, EventArgs e)
{
string[] words;
OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "Select your dictionary file";
fdlg.InitialDirectory = #"c:\";
fdlg.Filter = "Text files (*.txt)|*.txt";
fdlg.RestoreDirectory = true;
if (fdlg.ShowDialog() == DialogResult.OK)
words = File.ReadAllText(fdlg.FileName).Split(' ');
}
In this code the file the user picks is split on the space character. If you just wanted a string of the code and not each word change the declaration of words to
string words;
and the line where the variable gets assigned to
words = File.ReadAllText(fdlg.Filename);
hope this helps
I am trying to save my rich text box content to a a file. However I am getting the error when I am trying to save a new file. Save as works as expected. Any suggestions. Thank you
System.ArgumentException: 'Empty path name is not legal.'
My code for the save and save as button are as follows:
OpenFileDialog file_open = new OpenFileDialog();
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
filename = file_open.FileName;
RichTextBoxStreamType stream_type;
// Checks the extension of the file to save
if (filename.Contains(".txt"))
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveDlg = new SaveFileDialog();
string filename = "";
// To filter files from SaveFileDialog
saveDlg.Filter = "Rich Text File (*.rtf)|*.rtf|Plain Text File (*.txt)|*.txt";
saveDlg.DefaultExt = "*.rtf";
saveDlg.FilterIndex = 1;
saveDlg.Title = "Save the contents";
DialogResult retval = saveDlg.ShowDialog();
if (retval == DialogResult.OK)
filename = saveDlg.FileName;
else
return;
RichTextBoxStreamType stream_type;
if (saveDlg.FilterIndex == 2)
stream_type = RichTextBoxStreamType.PlainText;
else
stream_type = RichTextBoxStreamType.RichText;
richTextBox1.SaveFile(filename, stream_type);
MessageBox.Show("File Saved");
}
in my code i am writing text boxes data to a text file using save file dialog, which will save my text box data to a specified text file.and my problem is i need to retrieve back file data to respective text boxes when ever user required ...how can i do it?
private void SaveData_Click(object sender, EventArgs e)
{
// Stream myStream;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = "c:\\";
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if ((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
using (StreamWriter objWriter = new StreamWriter(myStream))
{
objWriter.Write(textBox1.Text);
objWriter.Write(",");
objWriter.Write(textBox2.Text);
objWriter.Write(",");
objWriter.Write(textBox3.Text);
objWriter.Write(",");
objWriter.Write(textBox4.Text);
MessageBox.Show("Details have been saved");
}
myStream.Close();
}
}
}
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
// Insert code to read the stream here.
textBox1.Text = (myStream).ToString();
textBox2.Text = ().ToString();
textBox3.Text = ().Tostring();
textBox4.text = ().Tostring();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
You need to use an OpenFileDialog Control and pass it to the ReadAllText Method ..
Here is an Example :
myAmazingTextBox.Text = File.ReadAllText(openFileDialog1.FileName);
Save the location where user saves data.\
Next time you should read the path first.
You can save the saveFileDialog1.FileName.
Use the code below to retrieve the text saved in the file (code changed within try block)
private void Retrieve_Click(object sender, EventArgs e)
{
//Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = "c:\\";
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
// Read all text stored in the file
string fileData = File.ReadAllText(openFileDialog1.FileName);
// As you are appending textbox data using comma as separator,
// so split the text read from file on comma separator
string[] parts = fileData.Split(',');
// as there were 4 textboxes, so after split, the 'parts' array should contain 4 elements, otherwise, the file/data is invalid
if(parts.Length != 4)
{
MessageBox.Show("Invalid source file.");
return;
}
// set the respective values into the textboxes
textBox1.Text = parts[0];
textBox2.Text = parts[1];
textBox3.Text = parts[2];
textBox4.text = parts[3];
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
I would like to suggest that you don't use comma as a separator as the user may enter text which contains comma in the content. I would suggest that you encode the text into Base64 string (which contains only A-Za-z0-9 with additional two characters which does not contain comma. So, you can separate the base64 encoded string with comma separator as then you will be 100% sure that comma is only the separator and not the part of content.
While reading, decode the base64 string and show into textboxes.
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.