browse folder and get user input to create a new file - c#

I want to create a file in a directory selected by the user and named it by the user input.
I tried FolderBrowserDialog but it didn't prompt me to give a file name:
FolderBrowserDialog fbd = new FolderBrowserDialog();
DialogResult result = fbd.ShowDialog();
string path = fbd.SelectedPath;
//string FileName; then concatenate it with the path to create a new file
how can I do that?

You want to create a new file in a folder, so you should:
ask the user to select a folder (with FolderBrowserDialog)
offer the user a way to type a file name, with an input field (separate from the folder dialog)
Then you concat those 2 infos to get your full file name.
Or you can use SaveFileDialog and check if the file already exists when the user has selected a file (with a File.Exists...). There is a property for displaying an alert when the file does not exists, but not on the other side.
So when you got the DialogResult, use File.Exists and you can alert the user.
Sample for this solution:
In this sample (I hope without errors, cannot test right now):
- I open the saveFileDialog on a button called SaveButton with the SaveButton_Click click method
- I have a SaveFileDialog component on my form, called saveFileDialog1. On this component, the event FileOK is associated to my saveFileDialog1_FileOk method
private void SaveButton_Click(object sender, EventArgs e)
{
// Set your default directory
saveFileDialog1.InitialDirectory = #"C:\";
// Set the title of your dialog
saveFileDialog1.Title = "Save file";
// Do not display an alert when the user uses a non existing file
saveFileDialog1.CheckFileExists = false;
// Default extension, in this sample txt.
saveFileDialog1.DefaultExt = "txt";
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
// DO WHAT YOU WANT WHEN THE FILE AS BEEN CHOSEN
}
}
// This method handles the FileOK event. It checks if the file already exists
private void saveFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
if (File.Exists(saveFileDialog1.FileName))
{
// The file already exists, the user must select an other file
MessageBox.Show("Please select a new file, not an existing one");
e.Cancel = true;
}
}

Related

Prevent user from browsing elsewhere in an OpenFileDialog

What I need to do is prevent users from browsing anywhere else then where I declare them to browse.
for example I have: ofd.InitialDirectory = Location; on button click.
Location for example being C:\Users\Chris\Pictures.
The thing is that I know that some users will try be clever and might go selecting things outside that folder I declare. Is there any way to prevent that from happening?
Possible workaround:
Just an if statement checking if the location of the selected file starts with the same Location I start them off in.
OpenFileDialog ofd = new OpenFileDialog();
private void button1_Click(object sender, EventArgs e)
{
string newPath = #"C:\Users\Chris\Pictures";
ofd.InitialDirectory = Location;
if (ofd.ShowDialog() == DialogResult.OK)
{
if (ofd.FileName.Contains(Location))
{
textBox1.Text = ofd.FileName;
}
else
{
MessageBox.Show("Please select a file that is located in the specified location (" + Location + ")"
, "Alert", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
You can't prevent users from navigating to another folder, you have to build an own OpenFileDialog if you want to do that. You can prevent though that the file isn't accepted.
You have to handle the FileOk event for that. You can check if the parent directory is the one you want it to be.
Something like this:
private void openFileDialog1_FileOk(object sender, System.ComponentModel.CancelEventArgs e)
{
string[] files = openFileDialog1.FileNames;
foreach (string file in files )
{
if (Path.GetDirectoryName(file) != yourRequiredPath)
{
e.Cancel = true;
break;
}
}
}
This is not possible.
You can't restrict users to prevent them to browse elsewhere where you don't wish to.
One possible way to fix this is to write your custom open dialog box with custom validations.
If you really want to prevent navigation in the file dialog the only way to do it would be to use the Common Item Dialog, provided by COM1, and give it an IFileDialogEvents and implement the OnFolderChanging event. To allow navigation, return S_OK and to deny navigation return something else.
1 "Provided by COM" as in the component object model, not some third party.

How to make UserControl add attachments

How to make user control in Windows application c#
I need make attachments files in form but I need use an user control when click
button browse and choose the files or image add user control in form ?
Add a button on the form and use OpenFileDialog, like that:
private void buttonGetFile_Click(object sender, EventArgs e)
{
OpenFileDialog dialog = new OpenFileDialog();
dialog.Filter = "Text files | *.txt"; // file types, that will be allowed to upload
dialog.Multiselect = false; // allow/deny user to upload more than one file at a time
if (dialog.ShowDialog() == DialogResult.OK) // if user clicked OK
{
String path = dialog.FileName; // get name of file
using (StreamReader reader = new StreamReader(new FileStream(path, FileMode.Open), new UTF8Encoding())) // do anything you want, e.g. read it
{
// ...
}
}
}

C# When creating a button that does File.CreateText method, how can I prompt a request for a user to enter File Name and write a text line?

I'm having problem to completely figure out File.CreatTextM Method.
What i'm trying to do is make a button that would prompt user to imput a text file name, prompt again to enter name, and finally create the text file in predestined location.
As far as i know in "Sring path =" you must predetermine name in the code, is there a command that opens a new window (or something) for user to input, so that i could store it to a variable and use in "Sring path ="
Or is there another approach for this?
if you are using windows form, then you can use saveFileDialog or for wpf win32 saveFileDialog, then you can get file name from this object. Use that filename to save your text.
use savefile dialog.
this code is from msdn
private void button2_Click(object sender, System.EventArgs e)
{
// Displays a SaveFileDialog so the user can save the Image
// assigned to Button2.
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "JPeg Image|*.jpg|Bitmap Image|*.bmp|Gif Image|*.gif";
saveFileDialog1.Title = "Save an Image File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if(saveFileDialog1.FileName != "")
{
// Saves the Image via a FileStream created by the OpenFile method.
System.IO.FileStream fs =
(System.IO.FileStream)saveFileDialog1.OpenFile();
// Saves the Image in the appropriate ImageFormat based upon the
// File type selected in the dialog box.
// NOTE that the FilterIndex property is one-based.
switch(saveFileDialog1.FilterIndex)
{
case 1 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Jpeg);
break;
case 2 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Bmp);
break;
case 3 :
this.button2.Image.Save(fs,
System.Drawing.Imaging.ImageFormat.Gif);
break;
}
fs.Close();
}
}
Unfortunately there is no InputBox in C#, other than if you are creating a custom one. Best solution is to place some textbox control in your form for same purpose. Then you can get their values in Button Click event and perform the logic.
You could create another Form with the necessary buttons and textboxes then show the form to the user, as referenced here : Original Post

Saving files with name read from text box. C#

I have created some code that saves my work to a text file, I was just wondering is there some way so that when I click 'Save' I can read in the text from richTextBox1and set it as the default file name, still with the 'txt' default file extension.
e.g. When I click 'save' the folder dialog comes up and asks you to name your file, just as it would if you were using Word for example, I want that box to already have the text from my richTextBox1 in.
Thanks.
private void saveToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog save = new SaveFileDialog();
save.InitialDirectory = "C:\\To-Do-List";
save.Filter = "Text Files (*.txt)|*.txt";
save.DefaultExt = ".txt";
DialogResult result = save.ShowDialog();
if (result == DialogResult.OK)
{
using (StreamWriter SW = new StreamWriter(save.FileName))
{
SW.WriteLine(richTextBox1.Text);
SW.WriteLine(richTextBox2.Text);
SW.WriteLine(richTextBox3.Text);
SW.WriteLine(richTextBox4.Text);
SW.WriteLine(richTextBox5.Text);
SW.Close();
}
}
Just set the FileName property on your SaveFileDialog.
Add
save.FileName = String.Format("{0}.txt", richTextBox1.Text);
Before you call ShowDialog.

How can i check if file is exist ask the user if to destroy it and create the same one again or not?

This is the code:
private void beginOperationToolStripMenuItem_Click(object sender, EventArgs e)
{
changeFileNameToolStripMenuItem.Enabled = false;
if (File.Exists(fullDefaultDirectory))
{
File.Delete(fullDefaultDirectory);
}
ffmp.Start(fullDefaultDirectory, 25);//"test.avi", #"d:\", 25);
timer1.Enabled = true;
startStop = true;
}
Now i check if the file exist and delete it but thats not good way since i need a file to be on the hard disk.
So what i want to do is:
If the fie exist ask the user if to delete it or run over it with the same name.
If deleted open the savedialog and let the user to set a new file name.
If not deleted just run over the existing file and create the same file name.
This is the savedialog i already have:
private void changeFileNameToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "Avi|*.avi";
saveFileDialog1.Title = "Save an Avi File";
saveFileDialog1.ShowDialog();
// If the file name is not an empty string open it for saving.
if (saveFileDialog1.FileName != "")
{
//outputFileName = Path.GetFileName(saveFileDialog1.FileName);
//outputDirectory = Path.GetDirectoryName(saveFileDialog1.FileName);
fullDefaultDirectory = saveFileDialog1.FileName;
Options_DB.Set_Video_File(fullDefaultDirectory);
}
}
But im talking about a situation when the user didnt change anything and the variable fullDefaultDirectory contain the same directory and file name then let the user to decide if to delete or run over it .
fullDefaultDirectory always contain a file name since i have a settings file name text file where i save the directory and file name the user selected.
If he didnt select anything the default is some file i did to be default and if he selected a file it will create the file the user selected.
I need to solve the case where the file is already exist.
The SaveFileDialog class already covers this with the OverwritePrompt property, which will cause the dialog to ask the user if they're sure they want to overwrite an existing file.

Categories