Opening a file in a tab - c#

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.

Related

Application freezes when I open a file dialog

I want it so that when the user clicks on the button and opens an image, the image gets copied to another location and the filepath of the copied image is saved inside 'Properties.Settings.Default.custombgfilepath'
Here is my code:
private void Button2_Click(object sender, EventArgs e)
{
//check for openfile dialog result
if (openFileDialog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
textBox1.Text = openFileDialog1.FileName;
//initialize destination
string destination = #"C:\Launchicity\";
//Get filename
string filename = Path.GetFileName(openFileDialog1.FileName);
//get filepath
string filepath = destination + filename;
if (!File.Exists(filepath))
{
File.Copy(openFileDialog1.FileName, filepath);
Properties.Settings.Default.custombgfilepath = filepath;
Properties.Settings.Default.Save();
}
else
{
Properties.Settings.Default.custombgfilepath = filepath;
Properties.Settings.Default.Save();
}
}
}
Here is the Windows Form Designer auto genertaed code for openfiledialog1:
//
// openFileDialog1
//
this.openFileDialog1.Filter = "\"PNG (*.png)|*.png|JPG (*.jpg)|*.jpg\"";
this.openFileDialog1.Title = "Browse Image";
this.openFileDialog1.FileOk += new System.ComponentModel.CancelEventHandler(this.OpenFileDialog1_FileOk);
When I click on the button however, the application freezes.
Can you please help me?
Thanks
More questions talk to me. Pls send me feedback ;) try this:
(Edited)
using system.IO
private void button1_Click(object sender, EventArgs e)
{
//check for openfile dialog result
this.openFileDialog1.Filter = "\"PNG (*.png)|*.png|JPG (*.jpg)|*.jpg\"";
this.openFileDialog1.Title = "Browse Image";
openFileDialog1.ShowDialog();
}
private void openFileDialog1_FileOk(object sender, CancelEventArgs e)
{
textBox1.Text = openFileDialog1.FileName;
//initialize destination
string destination = #"C:\Launchicity\";
//Get filename
string filename = Path.GetFileName(openFileDialog1.FileName);
//get filepath
string filepath = destination + filename;
if (!File.Exists(filepath))
{
File.Copy(openFileDialog1.FileName, filepath);
//Properties.Settings.Default.custombgfilepath = filepath; i dont have custombgfilepath
Properties.Settings.Default.Save();
}
else
{
//Properties.Settings.Default.custombgfilepath = filepath; i dont have custombgfilepath
Properties.Settings.Default.Save();
}
}

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

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.

Trying to save file without using SaveFileDialog

I am creating a text editor and i am stuck on the SaveFileDialog window opening
and asking to overwrite the current file open.
I have seen all the similar questions asked like this on SO but none have been able to help me. I have even tried the code from this question: "Saving file without dialog" Saving file without dialog
I got stuck on my program having a problem with FileName.
Here is the code i have currently
namespace Text_Editor
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
richTextBox1.Clear();
}
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
StreamWriter writer = new StreamWriter(save.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
}
}
So my question is how can i modify my code so that i can save a file currently open without having the SaveFileDialog box opening everytime?
I do understand that it has something to do with the fact that i'm calling .ShowDialog but i don't know how to modify it.
When opening the file, save the FileName in a form-level variable or property.
Now while saving the file, you can use this FileName instead of getting it from a FileOpenDialog.
First declare a variable to hold filename at form level
// declare at form level
private string FileName = string.Empty;
When opening a file, save the FileName in this variable
private void openToolStripMenuItem_Click(object sender, EventArgs e)
{
OpenFileDialog open = new OpenFileDialog();
open.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
open.Title = "Open File";
open.FileName = "";
if (open.ShowDialog() == DialogResult.OK)
{
// save the opened FileName in our variable
this.FileName = open.FileName;
this.Text = string.Format("{0}", Path.GetFileNameWithoutExtension(open.FileName));
StreamReader reader = new StreamReader(open.FileName);
richTextBox1.Text = reader.ReadToEnd();
reader.Close();
}
}
And when doing SaveAs operation, update this variable
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saving = new SaveFileDialog();
saving.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saving.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
saving.Title = "Save As";
saving.FileName = "Untitled";
if (saving.ShowDialog() == DialogResult.OK)
{
// save the new FileName in our variable
this.FileName = saving.FileName;
StreamWriter writing = new StreamWriter(saving.FileName);
writing.Write(richTextBox1.Text);
writing.Close();
}
}
The save function can then be modified like this:
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if (string.IsNullOrEmpty(this.FileName))
{
// call SaveAs
saveAsToolStripMenuItem_Click(sender, e);
} else {
// we already have the filename. we overwrite that file.
StreamWriter writer = new StreamWriter(this.FileName);
writer.Write(richTextBox1.Text);
writer.Close();
}
}
In the New (and Close) function, you should clear this variable
private void newToolStripMenuItem_Click(object sender, EventArgs e)
{
// clear the FileName
this.FileName = string.Empty;
richTextBox1.Clear();
}
Create a new string variable in your class for example
string filename = string.empty
and then
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
if(string.IsNullOrEmpty(filename)) {
//Show Save filedialog
SaveFileDialog save = new SaveFileDialog();
save.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
save.Title = "Save File";
save.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (save.ShowDialog() == DialogResult.OK)
{
filename = save.FileName;
}
}
StreamWriter writer = new StreamWriter(filename);
writer.Write(richTextBox1.Text);
writer.Close();
}
The SaveFileDialog now only opens if fileName is null or empty
You will have to store the fact that you have already saved the file, e.g. by storing the file name in a member variable of the Form class you have. Then use an if to check whether you have already saved your file or not, and then either display the SaveFileDialog using ShowDialog() (in case you haven't) or don't and continue to save to the already defined file name (stored in your member variable).
Give it a try, do the following:
Define a string member variable, call it _fileName (private string _fileName; in your class)
In your saveToolStripMenuItem_Click method, check if it's null (if (null == _fileName))
If it is null, continue as before (show dialog), and after getting the file name, store it in your member variable
Refactor your file writing code so that you either get the file name from the file dialog (like before), or from your member variable _fileName
Have fun, C# is a great language to program in.
First, extract method from saveAsToolStripMenuItem_Click: what if you want add up a popup menu, speed button? Then just implement
public partial class Form1: Form {
// File name to save text to
private String m_FileName = "";
private Boolean SaveText(Boolean showDialog) {
// If file name is not assigned or dialog explictly required
if (String.IsNullOrEmpty(m_FileName) || showDialog) {
// Wrap IDisposable into using
using (SaveFileDialog dlg = new SaveFileDialog()) {
dlg.Filter = "Text Files (.txt)|*.txt|All Files (*.*)|*.*";
dlg.Title = "Save File";
dlg.FileName = m_FileName;
if (dlg.ShowDialog() != DialogResult.OK)
return false;
m_FileName = dlg.FileName;
}
}
File.WriteAllText(m_FileName, richTextBox1.Text);
this.Text = Path.GetFileNameWithoutExtension(m_FileName);
return true;
}
private void saveAsToolStripMenuItem_Click(object sender, EventArgs e) {
// SaveAs: always show the dialog
SaveText(true);
}
private void saveToolStripMenuItem_Click(object sender, EventArgs e) {
// Save: show the dialog when required only
SaveText(false);
}
...
}

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;

save the changes in notepad

i am making a notepad in c#. this is the save part of the file. but the problem is that if i modify the text and save again, it asks to save a new file instead of saving in original file.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (saveFileDialog1.ShowDialog() == DialogResult.OK && saveFileDialog1.FileName != "")
{
richTextBox1.SaveFile(saveFileDialog1.FileName, RichTextBoxStreamType.RichText);
}
}
Use a private field in your class that has the value of the last saved file
var currentFileName = "";
.....
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
saveFileDialog1.Title = "Save file";
saveFileDialog1.FileName = tabControl1.SelectedTab.Text;
saveFileDialog1.Filter = "TEXT|*.txt|DOC|*.doc|DOCX|*.docx|RICH TEXT FILE|*.rtf|ALL FILES|*.*";
saveFileDialog1.InitialDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
bool save = true;
if (string.IsNullOrEmpty(currentFileName))
{
var result = saveFileDialog1.ShowDialog();
if (result == DialogResult.OK && saveFileDialog1.FileName != "")
{
currentFileName = saveFileDialog1.FileName;
}
else
{
save = false;
}
}
if (save)
richTextBox1.SaveFile(currentFileName, RichTextBoxStreamType.RichText);
}
If you keep showing the save file dialog then this is what you get. (saveFileDialog1.ShowDialog())
Best would be:
Create internal string variable containing the path. (default is "") (or use tabControl1.SelectedTab.Text)
If path is not set, show file dialog, save result in path
If path is set, save file
set .OverWritePrompt to false for your SaveFileDialog
http://msdn.microsoft.com/en-us/library/system.windows.forms.savefiledialog.overwriteprompt.aspx

Categories

Resources