Create a (text) file using FolderBrowserDialog - c#

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);
}
}
}

Related

Form.ShowDialog Methode

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

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);

How to make sure user select specific folder and remove file extension from files in the selected folder?

What I have here is the user select a folder full of .txt files from a external drive and a dummy file is made with the filename to a local folder.
I have 2 questions regarding the code below.
How do I verify that the user select a specific folder?
How do I remove the .txt extension? The code copies the file name and creates the files but its labeled "text.txt.png" but I need it to read "text.png".
int g;
private void folderSelect()
{
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
FileInfo[] textFiles = files.GetFiles("*.txt");
while (g < textFiles.Length)
{
if (g <= textFiles.Length)
{
File.Create("path/" + (textFiles[g].Name + ".png"));
g++;
}
else
{
break;
}
}
}
Note: I tried using Path.GetFileNameWithoutExtension to remove the extension but Im not sure if i was using it correctly.
Any help would be appreciated. Thank you in advance.
const string NEW_PATH = "path/";
if (!Directory.Exists(NEW_PATH))
Directory.CreateDirectory(NEW_PATH);
const string PATH_TO_CHECK = "correctpath";
FolderBrowserDialog folder = new FolderBrowserDialog();
folder.RootFolder = Environment.SpecialFolder.MyComputer;
folder.ShowNewFolderButton = false;
folder.Description = "Select Folder";
if (folder.ShowDialog() == DialogResult.OK)
{
string pathPastDrive = folder.SelectedPath.Substring(Path.GetPathRoot(folder.SelectedPath).Length).ToLower();
// Here it depends on whether you want to check (1) that the path is EXACTLY what you want,
// or (2) whether the selected path just needs to END in the path that you want.
/*1*/ if (!pathPastDrive == PATH_TO_CHECK)
/*2*/ if (!pathPastDrive.EndsWith(PATH_TO_CHECK))
return; // or you can throw an exception if you want
foreach (string textFile in Directory.GetFiles(folder.SelectedPath, "*.txt"))
File.Create(NEW_PATH + Path.GetFileNameWithoutExtension(textFile) + ".png");
}
You can use GetFileNameWithoutExtension, and it makes it pretty easy.
Also, if you're already sure that your new folder exists, then you can elide the first three lines and replace NEW_PATH with "path/" in the last line.
To see the returned path just use the SelectedPath property, then you can compare it to whatever you had in mind. The # before the path just means I don't have to escape any characters, it's the same as "C:\\MyPath".
FolderBrowserDialog folder = new FolderBrowserDialog();
if (folder.ShowDialog() == DialogResult.OK)
{
if (folder.SelectedPath == #"C:\MyPath")
{
// DO SOMETHING
}
}
You already hit the nail on the head about the file name without extension, change this line:
File.Create("path/" + (textFiles[g].Name + ".png"));
To this:
File.Create("path/" + (Path.GetFileNameWithoutExtension(textFiles[g].Name) + ".png"));
Edit:
To get the folder name you already have the DirectoryInfo object so just use that:
DirectoryInfo files = new DirectoryInfo(folder.SelectedPath);
string folderName = files.Name;

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);
}
}

Categories

Resources