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);
Related
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.
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;
Here is my code;
private void button1_Click(object sender, EventArgs e)
{
string newFile =textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = "";
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.ShowDialog();
StreamWriter yazmaislemi = new StreamWriter(a1.FileName);
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
it is saving the text on Desktop but i want to save it to the following path:
C:\Users\esra.ur\Desktop\projee1
use save file dialog, so you can save your text in your specific directory
using System;
using System.ComponentModel;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApplication30
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
// When user clicks button, show the dialog.
saveFileDialog1.ShowDialog();
}
private void saveFileDialog1_FileOk(object sender, CancelEventArgs e)
{
// Get file name.
string name = saveFileDialog1.FileName;
// Write to the file name selected.
// ... You can write the text from a TextBox instead of a string literal.
File.WriteAllText(name, "test");
}
}
}
this code snippets is from this link http://www.dotnetperls.com/savefiledialog
I hope it will help
1) Wrap your show dialog to check the result.
if(a1.ShowDialog() == DialogResult.OK)
2) The SaveFileDialog has a property for setting an initial path. This is for the directory which will be shown when the dialog is first open. For the desktop you want to use the Environment.GetFolderPath like so.
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
3) Try to separate concerns:
private string OutputFile {get;set;}
private void button1_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(this.OutputPath))
{
SaveFileDialog a1 = new SaveFileDialog();
a1.FileName = textBox1.Text;
a1.Filter = "Text Files(*txt)|*.txt";
a1.DefaultExt = "txt";
a1.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
if(a1.ShowDialog() == DialogResult.OK)
{
this.OutputFile = ai.FileName
}
}
this.SaveFile(this.OutputFile);
}
private void SaveFile(string FileName)
{
string newFile = FileName;
string temp = newFile.Replace("YNATEST.", "");
using(StreamWriter yazmaislemi = new StreamWriter(temp))
{
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
}
}
The SaveFileDialog object has a property called InitialDirectory, which is a string you can specify, for example
SaveFileDialog a1 = new SaveFileDialog();
a1.InitialDirectory = #"C:\Users\esra.ur\Desktop\projee1";
If this directory doesn't exist, it will default back to documents. Be careful about writing a file even if the user tries to cancel. Hope this helps?
In response to your comment, it sounds like you want to hard code the destination file name. This is dangerous as you can get an exception if the directory doesn't exist, but you can use the following: (I'm not sure what you want to do with the file name)
'string newFile = textBox1.Text;
string temp = newFile.Replace("YNATEST.", "");
StreamWriter yazmaislemi = new StreamWriter(#"C:\Users\esra.ur\Desktop\projee1\" + temp + ".txt");
yazmaislemi.WriteLine(temp);
yazmaislemi.Close();
In this case you don't need the SaveFileDialog at all. I think this is what you're asking for, but it's dangerous to code in this way.
// Browses file with OpenFileDialog control
private void btnFileOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogCSV = new OpenFileDialog();
openFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();
openFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialogCSV.FilterIndex = 1;
openFileDialogCSV.RestoreDirectory = true;
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
this.txtFileToImport.Text = openFileDialogCSV.FileName.ToString();
}
}
In the code above, i browse for a file to open. What I want to do is, browse for a file, select it and then press ok. On clicking ok, i want to make a copy of the seleted file and give that duplicate file a .txt extension. I need help on achieving this.
Thanks
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
var fileName = openFileDialogCSV.FileName;
System.IO.File.Copy( fileName ,Path.Combine(Path.GetDirectoryName(fileName), Path.GetFileNameWithoutExtension(fileName)+".txt"));
}
Above code will copy selected file as txt with same name and in to same directory.
if you need to overwrite existing file with same name add another parameter to Copy method as true.
System.IO.File.Copy(source, destination, true);
You use File.Copy as follows,
File.Copy(openFileDialogCSV.FileName., openFileDialogCSV.FileName + ".txt");
Try this
private void btnFileOpen_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialogCSV = new OpenFileDialog();
openFileDialogCSV.InitialDirectory = Application.ExecutablePath.ToString();
openFileDialogCSV.Filter = "CSV files (*.csv)|*.csv|All files (*.*)|*.*";
openFileDialogCSV.FilterIndex = 1;
openFileDialogCSV.RestoreDirectory = true;
if (openFileDialogCSV.ShowDialog() == DialogResult.OK)
{
this.txtFileToImport.Text = openFileDialogCSV.FileName.ToString();
System.IO.File.Copy(this.txtFileToImport.Text,"C://123.txt")
}
}
123 can be changed by any file name that you want.
Here is my snippet:
private void btnBrowseCInv_Click(object sender, EventArgs e)
{
ofdBrowseVInv.Title = "Locate Customer Invoice File";
ofdBrowseVInv.Filter = "Portable Document Format (*.pdf)|*.pdf|All Files (*.*)|*.*";
ofdBrowseVInv.FileName = "";
ofdBrowseVInv.FilterIndex = 0;
ofdBrowseVInv.InitialDirectory = "";
ofdBrowseVInv.CheckFileExists = true;
ofdBrowseVInv.CheckPathExists = true;
if (ofdBrowseVInv.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
//txtInvoicePathCInv.Text = ofdBrowseVInv... What property should i use?
}
}
As you see below, once a user pick a file and click open. I want the selected path to show on the pointed text box which is named "txtInvoicePathCInv". Any idea?
I'm using Windows Application...
alt text http://img708.imageshack.us/img708/54/99763211.jpg
Use the FileName property:
txtInvoicePathCInv.Text = ofdBrowseVInv.FileName;
This will give you the whole path, but you can always just use the directory part of it, using Path.GetDirectoryName:
txtInvoicePathCInv.Text = Path.GetDirectoryName(ofdBrowseVInv.FileName);
string filename = System.IO.Path.GetFileName(ofdBrowseVInv.FileName);
string path = System.IO.Path.GetDirectoryName(ofdBrowseVInv.FileName);