Form.ShowDialog Methode - c#

I have created a software, which save some Information in an Excel File. The software has two possibilities:
To select the folder and then the software will create an Excel File with random name and there will save the data , or
To select an existed Excel File which is created from the user and there will save the data.
How to create a ONE ShowDialog to ask the user do you want to choose the folder or the file?!
Code that I have used to choose a Folder:
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
textBox3.Text = fbd.SelectedPath;
}
}
Code that I have used to choose a File:
OpenFileDialog excelFilename = new OpenFileDialog();
if (excelFilename.ShowDialog() == DialogResult.OK)
{
textBox3.Text = excelFilename.FileName;
}

Maybe something like this?:
MessageBoxResult result = MessageBox.Show("Ask user what he wants to do", "", MessageBoxButton.YesNo);
string path = null;
//MessageBoxResult.Yes means File, .No means Folder
if (result == MessageBoxResult.Yes)
{
//File-Picker
OpenFileDialog filePicker = new OpenFileDialog()
{
FileName = "Excel File",
DefaultExt = ".xls",
Filter = "Excel Document | *.xls"
};
if (filePicker.ShowDialog() == true)
{
path = filePicker.FileName;
}
}
else if (result == MessageBoxResult.No)
{
//Folder-Picker
CommonOpenFileDialog folderPicker = new CommonOpenFileDialog()
{
IsFolderPicker = true,
Multiselect = false
};
path = Path.Combine(folderPicker.FileName, DateTime.Now.ToString("yyyy-MM-ddTHH-mm-ss"));
//Create file in folder
File.Create(path);
}
if (path != null)
{
// Do something with path (file user selected/program created)
}
Make sure you have the using System.Windows, using Microsoft.Win32; and using System.IO; using's at the beginning of your program.
You also have to add the WindowsAPICodePack library to your project to use the folder-picker. You can do that with the NuGet manager. Here's the link to the library: WindowsAPICodePack - 1.1.1

Related

Save with different name in C# Form Application

I have problem when I try to save my spx file with different name.
I tried lots of ways but it did not work.
How can I save my voice recorder with different name ?
if (dataGridView1.Columns[e.ColumnIndex].Name == "Export")
{
using (var fbd = new FolderBrowserDialog())
{
DialogResult result = fbd.ShowDialog();
if (result == DialogResult.OK && !string.IsNullOrWhiteSpace(fbd.SelectedPath))
{
string files = fbd.SelectedPath;
string source = dataGridView1.Rows[e.RowIndex].Cells[6].Value.ToString();
string FileName = Path.GetFileName(source);
string DirectoryName = Path.GetDirectoryName(source);
try
{
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, FileName));
}
catch (Exception)
{
MessageBox.Show("You have same voice recorder in that file.");
}
}
}
}
You just have to specify a new filename in the File.Copy command.
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, "NewFileName"));
You just need to change the name on the end, if you need the user to input this name, you just have to put an new variable on the method
File.Copy(Path.Combine(DirectoryName, FileName), Path.Combine(files, newFileName));
Here if you want to use SaveFileDialog.
SaveFileDialog saveDialog = new SaveFileDialog();
saveDialog.ShowDialog();
CopyFile("C://", "New Text Document.txt", files, saveDialog.FileName);

Create a (text) file using FolderBrowserDialog

I created a notepad, however i want to save the file using the FolderBrowserDialog. Now i can't save the file because of this error: An unhandled exception of type 'System.NotSupportedException' occurred in mscorlib.dll
Additional information: The specified path is not supported.
this is the code i enterd:
private void Create_button_Click(object sender, EventArgs e)
{
DialogResult dialogResult = MessageBox.Show("Are you sure to make the file", "Sure?", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (dialogResult == DialogResult.Yes)
{
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
StreamWriter File = new StreamWriter(files + "." + groupBox3);
File.Write(textBox4);
}
}
else if (dialogResult == DialogResult.No)
{
}
}
can somebody help me?
a few things here to cause problems:
string[] files = Directory.GetFiles(openfiledalog1.SelectedPath);
Here you read the existing files in that directory. I thought you wanted to create a file? IN that case you provide a destination path, e.g.
var dest=Path.Combine(openfileDialog1.SelectedPath,"myfile.txt");
The following especially will not work:
StreamWriter File = new StreamWriter(files + "." + groupBox3);
You are passing a string array here. You need to pass a string as argument, not an array. See above. Also you try to name it like (which?) existing file + an extension determined by some groupBox3?
Writing the file, assuming that textBox4 contains the contents to be written, needs to be specified via the .Text property:
File.Write(textBox4.Text);
Please be specific as to which control or variable contains the desired output filename, which the contents, and what groupBox3 is supposed to provide.
Edit:
RadioButton suffix = groupBox3.Controls.OfType<RadioButton>().FirstOrDefault(n => n.Checked);
if (suffix == null)
MessageBox.Show("Please select a valid extension first");
else
{
var extension = suffix.Text;
FolderBrowserDialog openfiledalog1 = new FolderBrowserDialog();
if (openfiledalog1.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
var dest = Path.Combine(openfiledalog1.SelectedPath, "NewFile." + extension);
using (StreamWriter File = new StreamWriter(dest, false))
{
File.Write(textBox4.Text);
}
}
}

Selection of a folder path with C#

I have a WPF application in which i have this method:
public static string getFile(List<string> extensions)
{
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
string ext = "files (", filter = "";
foreach (string s in extensions)
{
ext += s + ",";
filter += "*." + s + ";";
}
ext += ")";
dlg.Filter =ext+"|"+ filter;
Nullable<bool> result = dlg.ShowDialog();
if (result == true)
{
return dlg.FileName;
}
else return null;
}
I need to add another simple method which returns a folder path in which i will save new file.
How can i do this?
What is the best way to do it?
SaveFileDialog is what you need. From MSDN link:
// Configure save file dialog box
Microsoft.Win32.SaveFileDialog dlg = new Microsoft.Win32.SaveFileDialog();
dlg.FileName = "Document"; // Default file name
dlg.DefaultExt = ".text"; // Default file extension
dlg.Filter = "Text documents (.txt)|*.txt"; // Filter files by extension
// Show save file dialog box
Nullable<bool> result = dlg.ShowDialog();
// Process save file dialog box results
if (result == true)
{
// Save document
string filename = dlg.FileName;
}
I'd suggest having a look at the free Ookii Dialogs for WPF. I've used it on commercial projects in the past and it's always worked really well. Native support for WPF obviously but also has a lot of options for customization and provides more consistency across different versions of Windows.

SaveFileDialog, file does not exist

I have to process an XML file (I am choosing a file with OpenFileDialog [code not present here] and when I click the second button the XML is processed to show a tree structure of that XML that has to be saved in the other file). But when I use SaveFileDialog , I want to enter a file name of the file which does not exist yet. How should I do that if I enter the filename that does not exits , an empty file will be created ?
private void button2_Click(object sender, EventArgs e)
{
SaveFileDialog fDialog = new SaveFileDialog();
fDialog.Title = "Save XML File";
fDialog.FileName = "drzewo.xml";
fDialog.CheckFileExists = false;
fDialog.InitialDirectory = #"C:\Users\Piotrek\Desktop";
if (fDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(fDialog.FileName.ToString());
}
string XMLdrzewo = fDialog.FileName.ToString();
XDocument xdoc = XDocument.Load(XMLdrzewo);
//// some code processing xml file
/// not ready yet, have to write to that file the tree
//structure of selected XML file
textBox2.Text = File.ReadAllText(XMLdrzewo);
When file does not exist I get FileNotFoundException was unhandled.
the code that creates your filename should be inside the if statement.
if (fDialog.ShowDialog == DialogResult.OK)
{
}
Then, you need to create a file first, eg var stream = File.Create(filename). Then you can fill that file with the "to be created stuff" and store the xml part in your newly created file.
Something like:
if (fDialog.ShowDialog() == DialogResult.OK)
{
using (var newXmlFile = File.Create(fDialog.FileName);
{
var xd = new XmlDocument();
var root = xd.AppendChild(xd.CreateElement("Root"));
var child = root.AppendChild(xd.CreateElement("Child"));
var childAtt = child.Attributes.Append(xd.CreateAttribute("Attribute"));
childAtt.InnerText = "My innertext";
child.InnerText = "Node Innertext";
xd.Save(newXmlFile);
}
}

Display a neat set of files in my application

I have a set of files written to a temporary directory which I want to display to the user. In this instance I wish them to be able to select a file and then have the option of saving it. Is there a decent control in C# for doing this?
I think you could use OpenFileDialog and FolderBrowserDialog for example:
using (OpenFileDialog dialog = new OpenFileDialog())
{
dialog.InitialDirectory = "c:\\";//your temp directory path
dialog.Title = "Select files to move/copy";
if (dialog.ShowDialog() == DialogResult.OK)
{
string[] files = dialog.FileNames;
using (FolderBrowserDialog save = new FolderBrowserDialog())
{
save.Description = "Select location to save files";
if (save.ShowDialog() == DialogResult.OK)
{
foreach (string file in files)
{
FileInfo finfo = new FileInfo(file);
File.Move(file, save.SelectedPath + finfo.Name);
}
}
}
}
}
Would a simple Open File Dialog be sufficent? You can restrict it to only show the files with your temporary extension. OpenFileDialog in C# gives some examples of use.

Categories

Resources