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();
}
}
Related
As a small beginner-ish project i'm making a simple program that can play .wav files, I've encountered an issue however where in stuck in a situation where the program gets the file path and name from one void but I need to use that string in another void, example code here:
public void ChooseFile_Click(object sender, EventArgs e)
{
OpenFile.InitialDirectory = #"C:\";
OpenFile.RestoreDirectory = true;
OpenFile.FileName = "";
OpenFile.Title = "Open .wav file";
OpenFile.Filter = "wav files (*.wav)|*.wav";
OpenFile.ShowDialog();
string fileName = OpenFile.FileName;
ChosenFileText.Text = fileName;
}
public void PlayButton_Click(object sender, EventArgs e)
{
SoundPlayer sound = new SoundPlayer(fileName);
sound.Play();
}
As you can see I need to use the fileName string with the SoundPlayer but currently I get the error:
"The name 'fileName' does not exist in the current context".
I've tried making it public and static but all I get is errors, does anyone know how I can work around this?
You have to define the variable inside the class so that everyone can access it.
string fileName="";
public void ChooseFile_Click(object sender, EventArgs e)
{
OpenFile.InitialDirectory = #"C:\";
OpenFile.RestoreDirectory = true;
OpenFile.FileName = "";
OpenFile.Title = "Open .wav file";
OpenFile.Filter = "wav files (*.wav)|*.wav";
OpenFile.ShowDialog();
fileName = OpenFile.FileName;
ChosenFileText.Text = fileName;
}
public void PlayButton_Click(object sender, EventArgs e)
{
SoundPlayer sound = new SoundPlayer(fileName);
sound.Play();
}
I have set up a program that so far can browse for the location of a file that possesses data in a text file holding the locations of other files which then shows me if they exist, are missing or are a duplicate inside listboxes. The next step is to enable the user to select files in the checked list boxes and being given the option to either move or copy. I have already made buttons which allow this but I want to be able to use them for the checked boxes I the list boxes.(p.s) please ignore any comments I have made in the code they are just previous attempts of doing other things in the code.
My code so far:
namespace File_existence
{
public partial class fileForm : Form
{
private string _filelistlocation;
public fileForm()
{
InitializeComponent();
}
private void checkedListBox1_SelectedIndexChanged(object sender, EventArgs e)
{
}
public void fileForm_Load(object sender, System.EventArgs e)
{
_filelistlocation = textBox1.Text;
}
private void button1_Click(object sender, System.EventArgs e)
{
//GetDuplicates();
checkedListBox1.Items.Clear();
listBox2.Items.Clear();
ReadFromList();
}
private void GetDuplicates()
{
DirectoryInfo directoryToCheck = new DirectoryInfo(#"C:\\temp");
FileInfo[] files = directoryToCheck.GetFiles("*.*", SearchOption.AllDirectories);
var duplicates = files.GroupBy(x => x.Name)
.Where(group => group.Count() > 1)
.Select(group => group.Key);
if (duplicates.Count() > 0)
{
MessageBox.Show("The file exists");
FileStream s2 = new FileStream(_filelistlocation, FileMode.Open, FileAccess.Read, FileShare.Read);
// open _filelistlocation
// foreach line in _filelistlocation
// concatenate pat hand filename
//
}
}
public void ReadFromList()
{
int lineCounter = 0;
int badlineCounter = 0;
using (StreamReader sr = new StreamReader(_filelistlocation))
{
String line;
while ((line = sr.ReadLine()) != null)
{
string[] values = line.Split('\t');
if (values.Length == 2)
{
string fullpath = string.Concat(values[1], "\\", values[0]);
if (File.Exists(fullpath))
checkedListBox1.Items.Add(fullpath);
else
listBox2.Items.Add(fullpath);
++lineCounter;
}
else
++badlineCounter;
//Console.WriteLine(line);
}
}
}
//StreamReader files= new StreamReader(File)();
private void listBox1_SelectedIndexChanged(object sender, System.EventArgs e)
{
}
private void button2_Click(object sender, System.EventArgs e)
{
FolderBrowserDialog folderBrowserDlg = new FolderBrowserDialog();
folderBrowserDlg.ShowNewFolderButton = true;
DialogResult dlgResult = folderBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = folderBrowserDlg.SelectedPath;
Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
try
{
string fileName = "filetest1.txt";
string sourcePath = #"C:\Temp\Trade files\removed";
string targetPath = #"C:\Temp\Trade files\queued";
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath,fileName);
System.IO.File.Copy(sourceFile, destFile, true);
}
catch (IOException exc)
{
MessageBox.Show(exc.Message);
}
}
private void button3_Click(object sender, System.EventArgs e)
{
try
{
string sourceFile = #"C:\Temp\Trade Files\queued\filetest1.txt";
string destinationFile = #"C:\Temp\Trade Files\processed\filetest1.txt";
System.IO.File.Move(sourceFile, destinationFile);
}
catch(IOException ex){
MessageBox.Show(ex.Message);//"File not found"
}
}
private void button4_Click(object sender, System.EventArgs e)
{
OpenFileDialog fileBrowserDlg = new OpenFileDialog();
//folderBrowserDlg.ShowNewFolderButton = true;
//folderBrowserDlg.SelectedPath = _filelistlocation;
fileBrowserDlg.FileName = textBox1.Text;
DialogResult dlgResult = fileBrowserDlg.ShowDialog();
if (dlgResult.Equals(DialogResult.OK))
{
textBox1.Text = fileBrowserDlg.FileName;
File_existence.Properties.Settings.Default.Save();
// Environment.SpecialFolder rootFolder = folderBrowserDlg.RootFolder;
}
}
private void button5_Click(object sender, System.EventArgs e)
{
if (!textBox1.Text.Equals(String.Empty))
{
if (System.IO.Directory.GetFiles(textBox1.Text).Length > 0)
{
foreach (string file in System.IO.Directory.GetFiles(textBox1.Text))
{
checkedListBox1.Items.Add(file);
}
}
else
{
checkedListBox1.Items.Add(String.Format("No file found: {0}", textBox1.Text));
}
}
}
}
}
The task I need to do is that the files that appear in the checked list box need to usually be moved or copied to another directory. That is fine as I can already do that with what I have coded, but what it does is it will move or copy all of the files in the checked list box. What I want to do is enable the user to only be able to select which files they what to move or copy through checking the checked list box so that only those files will be moved or copied.
EDIT: Could it be checkedListBox.checked items?
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);
}
...
}
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.
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
this.textBox1.Text = result + "";
}
It just returns "OK"
What am I doing wrong? I wish to get the PATH to the file and display it in a text box.
The ShowDialog method returns whether the user pressed OK or Cancel. This is useful information, but the actual filename is stored as a property on the dialog
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog newOpen = new OpenFileDialog();
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
this.textBox1.Text = newOpen.FileName;
}
}
You need to access the filename:
string filename = newOpen.FileName;
or filenames, if you allowed multiple file selection:
newOpen.FileNames;
Ref.: OpenFileDialog Class
private void button1_Click(object sender, System.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.
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file. Error: " + ex.Message);
}
}
}
You need to read the FileName property of the OpenFileDialog instance. This will get you the path of the selected file.
Here is an example of using an existing file as a default, and getting a new file back:
private string open(string oldFile)
{
OpenFileDialog newOpen = new OpenFileDialog();
if (!string.IsNullOrEmpty(oldFile))
{
newOpen.InitialDirectory = Path.GetDirectoryName(oldFile);
newOpen.FileName = Path.GetFileName(oldFile);
}
newOpen.Filter = "eXtensible Markup Language File (*.xml) |*.xml"; //Optional filter
DialogResult result = newOpen.ShowDialog();
if(result == DialogResult.OK) {
return newOpen.FileName;
}
return string.Empty;
}
Path.GetDirectoryName(file) : Return path
Path.GetFileName(file) : Return filename