How to close a text file that is opened through openDialogBox? - c#

I have created a button that opens a text file through openDialogBox1 and display the content in a listBox. Then I wanted to create another button to close this file, but I couldn't figure out what code to use. Can anyone help me please? Thank you.
Here is a sample of my openFile button code :
private void openButton_Click(object sender, EventArgs e)
{
try
{
StreamReader inputFile;
string File;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.DefaultExt = "txt";
openFileDialog1.Filter = "Text Files (*txt)|*txt";
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
inputFile = File.OpenText(openFileDialog1.FileName);
fileListBox.Items.Clear();
while (!inputFile.EndOfStream)
{
File = inputFile.ReadLine();
fileListBox.Items.Add(File);
}
inputFile.Close();
}
}
catch
{
MessageBox.Show("Invalid File!");
}
}

Declare StreamReader inputFile; globally so it is available in the second button click.
However, the file should be opened and closed as soon as you are done with it to release resources. Plus, you don't know, the second button may never get clicked.

Related

Open an existing text file in WPF and C#

I have a program that enables a user to search text files in an open file dialog. The user is then able to open an existing text file they choose and edit it. However, my problem is that when they file opens it appears blank. What am I missing?
private void Open_Click(object sender, RoutedEventArgs e)
{
TextBox openText = new TextBox();
var OpenFile = new Microsoft.Win32.OpenFileDialog();
Nullable<bool> Success = OpenFile.ShowDialog();
OpenFile.DefaultExt = ".txt";
OpenFile.Filter = "Text documents (.txt)|*.txt";
if (Success.HasValue && Success.Value)
{
openText.Text = OpenFile.FileName;
}
else
{
//cannot open file
}
}
Replace this:
openText.Text = OpenFile.FileName;
with this:
openText.Text = System.IO.File.ReadAllText(OpenFile.FileName);
Use File.ReadAllText()
openText.Text = File.ReadAllText(OpenFile.FileName);

SaveFileDialog does not save the filename or path

I want to use a SaveFileDialog and when clicking on the Save Button I want to save the filename and the path into seperate variables. Here is the code:
private void Button_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.FileName = "SaveFile";
saveFileDialog1.DefaultExt = ".txt";
saveFileDialog1.Filter = "Text Files (*.txt)|*.txt";
saveFileDialog1.Title = "Save a Text File";
saveFileDialog1.FileOk += saveFileDialog1_FileOk;
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
string filename = System.IO.Path.GetFileName(saveFileDialog1.FileName);
string name = saveFileDialog1.FileName;
var test = System.IO.Path.GetDirectoryName(saveFileDialog1.FileName);
}
The dialog opens and it triggers the saveFileDialog1_FileOk Event but I get an empty string for the filename and the solution for getting the path (without filename) does not work. What am I doing wrong?
The main problem you have is using 2 instance of SaveFileDialog.
You show one dialog and then try to read File from another dialog that is obviously empty.
Pay attention that in your button click you are creating a new local instance and show it, and then in FileOk you are using another instance that seems to be a form level member.
Fix 1:
You can simply remove SaveFileDialog saveFileDialog1 = new SaveFileDialog(); because it seems you have saveFileDialog1 as a member of your form.
Fix 2:
You can use SaveFileDialog this way:
var sfd= new SaveFileDialog();
//Other initializations ...
//sfd.Filter= "Text files (*.txt)|*.txt|All files (*.*)|*.*";
//sfd.DefaultExt = "txt";
if(sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
MessageBox.Show(sfd.FileName);
//ِDo something for save
}
else
{
//Do something for cancel if you want
}
Then you can access to selected file using FileName property, for example MessageBox.Show(sfd.FileName);
Check this example from MSDN (https://msdn.microsoft.com/de-de/library/system.windows.forms.savefiledialog(v=vs.110).aspx):
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
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.
myStream.Close();
}
}
}
You only have to check the return value of saveFileDialog1.ShowDialog() to know whether the user has clicked ok or not.
Then, you can use the FileName property which contains the selected file path.
EDIT: To get the folder path of the file, you can use this:
string folderPath = new DirectoryInfo(saveFileDialog1.FileName).Name;

Opening a file in a tab

I'm still learning, but I'd like to open a file in a new tab with the name of the file in the tab name. I can only open a file when I have a tab open already. Here is what I have at the moment.
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
Stream myStream;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
string strfilename = openFileDialog1.FileName;
string filetext = File.ReadAllText(strfilename);
GetActiveEditor().Text = filetext;
}
}
}
Any help would be greatly appreciated.
Also, if you have any tips on saving a file in a selected tab, that'd be great.

Beginners help C# showing a filepath in text box

I'm new to programming and am using C# and Visual Studio Express 2012. I am creating a windows form and have inserted a button which runs open file dialog when clicked. I have a text box on the form that I'd like to have show the file path of the file that the user selected. I have found some code examples on this site but struggle to understand where they should be placed in the code structure as the examples are often standalone snippets. I hope its not too dumb a question!
Thanks in advance
Lee
The answer in case it's of use to anyone was.......
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
using (FileDialog fileDialog = new OpenFileDialog())
{
if (DialogResult.OK == fileDialog.ShowDialog())
{
string filename = fileDialog.FileName;
textBox1.Text = fileDialog.FileName;
}
}
}
}
Your OpenFileDialog has property FileName that contains the path of the selected file, assign that to your TextBox.Text
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
yourTextBox.Text = openFileDialog.FileName;
}
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
if(openFileDialog1.ShowDialog() == DialogResult.OK)
textbox.text = openFileDialog1.FileName;

Add prompt after user selects file

I have added an open file dialog box to my client application so that the used can select a specific file they want to send to the web service.
However the file gets sent the moment the file has been selected, whereas I would like to have a secondary prompt e.g. "Send - 'file name' Button Yes. Button No." to pop up after they have selected the file.
This would be incase the user selected the wrong file they would have a chance to see which one they selected.
So far I have the following code -
private void button1_Click(object sender, EventArgs e)
{
//Read txt File
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
myReader.Close();
string csv = File.ReadAllText(openFileDialog1.FileName);
I need the prompt to come up after they have selected the file but not sure how to do this so any input would be greatly appreciated.
you need to add the second check manually after the first dialog:
private void button1_Click(object sender, EventArgs e)
{
//Read txt File
openFileDialog1.Filter = "Text Files (*.txt)|*.txt|All Files (*.*)|*.*";
openFileDialog1.FilterIndex = 1;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
if (MessageBox.Show("Message", "Title",MessageBoxButtons.YesNo)==DialogResult.Yes)
{
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
myReader.Close();
string csv = File.ReadAllText(openFileDialog1.FileName);
etc etc
Information on MessageBox.Show. You can get information on the possible results/options from here.
You could ensure that the user sees the file to be uploaded by making the message something like:
"Are you sure you want to upload " + openFileDialog1.FileName;
MessageBox.Show(...) is the method you're looking for.
You can use a message box:
if (MessageBox.Show(string.Format("Upload {0}, are you sure?", openFileDialog1.FileName), "Please Confirm", MessageBoxButtons.YesNo) == DialogResult.Yes)
{
// ...
}
A sample of the code modified.
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
DialogResult dr = MessageBox.Show(message, caption, MessageBoxButtons.YesNo);
if(dr == DialogResult.Yes )
StreamReader myReader = new StreamReader(openFileDialog1.FileName);
// more code
else
// do something else

Categories

Resources