C# winform File.Copy from a SaveDialog - c#

I am attempting to copy a .txt from my application directory or some kind an export feature to users desire path and filename using savedialog on C# my code is below.
private void button2_Click(object sender, EventArgs e)
{
string directory = AppDomain.CurrentDomain.BaseDirectory + "output.txt";
using (SaveFileDialog dialog = new SaveFileDialog())
{
dialog.Filter = "txt files (*.txt);
dialog.FilterIndex = 2;
dialog.RestoreDirectory = true;
if (dialog.ShowDialog() == DialogResult.OK)
{
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
}
}
}
But I am getting an error
The given path's format is not supported.
I am new with C# and want to understand this error and in addition, I want to set the file name extention default as .txt also, any suggestion would be great.

There are a couple of things you need to change.
First, of course, is your copy call. This line makes no sense
File.Copy(directory, Path.GetDirectoryName(dialog.FileName) + dialog.FileName);
dialog.FileName contains already the full file name of your destination file. So there is no need to extract the directory and then add all the path again. Write just
File.Copy(directory, dialog.FileName);
But this creates a possible error. What if your user doesn't change the destination folder to another directory? You end up writing on the same file you want to read.
So I would add a sanity check like this
if(directory == dialog.FileName)
MessageBox.Show("Copy","Choose a different output folder");
else
File.Copy(directory, dialog.FileName);
Finally, if you want to force the output file to have always the .TXT extension you could add this line to the SaveDialog configuration
// Fix also your filter property. The one you have is invalid
dialog.Filter = "txt files (*.txt)|*.txt";
dialog.FilterIndex = 0; // 2 ?? There is no index 2 in your filter string
dialog.RestoreDirectory = true;
// Force the .TXT extension
dialog.AddExtension = true;

Related

Unable to create a text file in windows form, getting error 'System.ArgumentException'

I've made a button so when I click it, it opens up a directory from which I can create a text file, I click the button, it opens the directory fine, I can name the text file what I want and click save, but then I get an error saying "An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll"
This is my code:
private void createAlgorithmsAndComplexityNotesToolStripMenuItem_Click(object sender, EventArgs e)
{
SaveFileDialog sfd = new SaveFileDialog();
sfd.Filter = "Text File|*.txt";
sfd.FileName = "Algorithms And Complexity Lecture Notes";
sfd.Title = "Algorithms And Complexity Lecture Notes";
if (sfd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string path = sfd.FileName;
StreamWriter write = new StreamWriter(File.Create("C:\\Users\antho\\Desktop\\Folder\\Uni\\Programming and data structures\\Assignment 2\\Modules"));
write.Write(writeFile);
write.Close();
}
}
First of all put your path in a variable and check if the directory exists at all (if not, create it).
(note the single backslashes)
string path = #"C:\Users\antho\Desktop\Folder\Uni\Programming and data structures\Assignment 2\Modules";
string fileName = sfd.FileName;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
Secondly, use Path.Combine() for constructing paths. The path that you set in the File.Create must end with a filename.
I also recommend using File.WriteAllText() for simple file creation (like in your code). With that you don't have to bother with closing it.
File.WriteAllText(Path.Combine(path, fileName), writeFile);
Your problem is with the file path you provided.
"C:\\Users\antho\\Desktop\\Folder\\Uni\\Programming and data structures\\Assignment 2\\Modules"
You forgot to escape a backslash here: Users\antho.
In this case, \a is interpreted as a single character, which is illegal in a file name. Not even sure if that is an existing character.

Make user browse and select a txt file for processing in c#

I want the user to locate a txt file on his computer which will later be used by my code for analysis. Is there a way to do that? One possible way is to make user enter the path of txt file. But that's not how I would prefer it
Thanks
string filename;
var loadDialog = new OpenFileDialog { Filter = "Text File|*.txt", InitialDirectory = #"C:\Your\Start\Directory\" };
if (loadDialog.ShowDialog() == DialogResult.OK)
filename = loadDialog.FileName;

Copy and Rename files in WPF C#

I'm using System.Windows.Forms.OpenFileDialog in my WPF application to select images. When user select an image, I'm displaying file name of selected file in a textbox as below.
OpenFileDialog fileDialog = new OpenFileDialog();
fileDialog.Title = "Select image";
fileDialog.InitialDirectory = "";
fileDialog.Filter = "Image Files (*.gif,*.jpg,*.jpeg,*.bmp,*.png)|*.gif;*.jpg;*.jpeg;*.bmp;*.png";
fileDialog.FilterIndex = 1;
fileDialog.RestoreDirectory = true;
if (fileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
txtImagePath.Text = fileDialog.FileName;
}
I have a button as Save in my application. When user click on this button, I need to rename this file to another name and copy it to another directory in my hard drive.
How can I achieve this?
Using File.Copy and methods in the Path class to extract the relevant part of your file
string newDir = #"D:\temp";
string curFile = Path.GetFileName(txtImagePath.Text);
string newPathToFile = Path.Combine(newDir, curFile);
File.Copy(txtImagePath.Text, newPathToFile);
Now the rename operation on the current dir using File.Move
string curDir = Path.GetDirectoryName(textImagePath.Text);
File.Move(txtImagePath.Text, Path.Combine(curDir, "NewNameForFile.txt"));
This code could be improved introducing some error handling
If you want to copy directly the old file in the new dir using the new name then you could write simply
string newPathToFile = #"D:\temp\NewNameForFile.txt";
File.Copy(txtImagePath.Text, newPathToFile);
and then do the rename on the current dir.
How about using:
System.IO.File.Copy
Alternatively, you can start a batch file, using processInfo
You can use File.Copy. Here are the details: http://msdn.microsoft.com/en-us/library/c6cfw35a.aspx. It takes the source file and copies it to a destination, possibly under a new name.

Save File Dialog , restrict name

my program has a save file option which is shown below :
//Browse for file
SaveFileDialog ofd = new SaveFileDialog();
ofd.Filter = "CSV|*.csv";
ofd.DefaultExt = ".csv";
DialogResult result = ofd.ShowDialog();
string converted = result.ToString();
if (converted == "OK")
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
if I write the file name as "example" it saves correctly as a .csv however if I set the name as "example.txt" it saves as a text file , I've looked on msdn etc but even setting the default extension doesn't prevent this , any ideas on how to only allow files of .csv to be saved ?
You could use the FileOk event to check what your user types and refuse the input if it types something that you don't like.
For example:
SaveFileDialog sdlg = new SaveFileDialog();
sdlg.FileOk += CheckIfFileHasCorrectExtension;
sdlg.Filter = "CSV Files (*.csv)|*.csv";
if(sdlg.ShowDialog() == DialogResult.OK)
Console.WriteLine("Save file:" + sdlg.FileName);
void CheckIfFileHasCorrectExtension(object sender, CancelEventArgs e)
{
SaveFileDialog sv = (sender as SaveFileDialog);
if(Path.GetExtension(sv.FileName).ToLower() != ".csv")
{
e.Cancel = true;
MessageBox.Show("Please omit the extension or use 'CSV'");
return;
}
}
The main advantage of this approach is that your SaveFileDialog is not dismissed and you could check the input without reloading the SaveFileDialog if something is wrong.
BEWARE that the SaveFileDialog appends automatically your extension if it doesn't recognize the extension typed by your user. This means that if your user types somefile.doc then the SaveFileDialog doesn't append the .CSV extension because the .DOC extension is probably well known in the OS. But if your user types somefile.zxc then you receive as output (and also in the FileOk event) a FileName called somefile.zxc.csv
can you not just force the .csv filetype by going like so in the last block of code?
if (converted == "OK")
{
if (ofd.FileName.toString.EndsWith(".csv")<1)
{
Master_Inventory_Export_savePath.Text = ofd.FileName + ".csv";
}
else
{
Master_Inventory_Export_savePath.Text = ofd.FileName;
}
}
Note - untested, but should give you a starting point....
Set the property AddExtension to true.
ofd.AddExtension = true;

How to copy Access Database File?

I want to copy existing Acccess Database file from my project into another location using SaveFileDialog in C#.
I wrote following code segments:
SaveFileDialog s = new SaveFileDialog();
s.Title = "SaveFile As...";
s.Filter = "Access Documents (*.accdb)|*.accdb|Others Documents (*.*)|*.*;";
string filenames = "MyAccDB.accdb";
s.FileName = filenames;
if (s.ShowDialog() != DialogResult.Cancel)
{
File.Copy(#"MyAccDB.accdb", s.FileName);
}
But it doesn't work and not saving.
How can I save access DB file into another location?
Give full path. See examples here.
File.Copy(#"C:\...\MyAccDB.accdb", #"C:\...\MyAccDB.accdb");
Just simple,
File.Copy("Source file Path","Destination file path)";
That's all.

Categories