Access Database Backup using C# - c#

Hi I created a wpf application in C# using Access as the db. I am trying to create a backup where the user will click on the backup button and then the file explorer window will open so that the user can choose where they want to save their backup. I looked on the site and there are several topics on this but I did not see one where the file explorer was called. I know how to create a backup copy using the following:
private void BackupDatabase_Click(object sender, RoutedEventArgs e)
{
File.Copy("Results_West.mdb", "Results_WestBak.mdb", true);
}
The above works and saves the backup where the executable is located but I'm not sure how to call windows file explorer and then do the save where the user wants to like when you're saving other files. Any ideas on this would be helpful.
Thanks.

You should use a SaveFileDialog located under the Microsoft.Win32 namespace.
The SaveFileDialog doesn't actually do any saving work, it's just a dialog to help you get a destination file path.
SaveFileDialog.ShowDialog() will show the dialog, and when the user closes the dialog (eg. by accepting or declining), it will return a nullable boolean value to indicate if the dialog was accepted, declined or cancelled.
If ShowDialog() returns true, you should have a file path (string) that you can use in your copy method.
I hope this helps you understand. I have attached some code to help.
public void BackupDatabase()
{
// The relative or full path of the database that you want to copy
string fileToBackup = "Results_West.mdb";
// The directory the save file dialog opens by default
// --- Optional ---
string initialFilePath = #"C:\Backup";
// Initialize the sfd
SaveFileDialog sfd = new SaveFileDialog
{
Title = "Choose a destination for your backup.",
Filter = "Microsoft Access File|*.mdb",
// --- Optional ---
InitialDirectory = initialFilePath,
};
// sfd.ShowDialog() returns a nullable bool
// If it returns true, you should have enough information to work with.
// We need to escape if the result is not true.
if (sfd.ShowDialog() != true)
{
return;
}
try
{
// sfd.FileName is the full path that the user selected.
// 3rd parameter (true) specifies overwrite
File.Copy(fileToBackup, sfd.FileName, true);
}
catch
{
// Failed to copy file.
}
}

Related

C# WPF Have User select file then use the functions within that file

I'm new to using C# and WPF so I apologize if my terminology is incorrect.
I want trying to make a program to automate small businesses workflows, the base application is the same for everyone, but how their order data is structured is going to be different.
So, my goal would be to build them a custom file that contains function on how to parse their order data, then have the user drag and drop that file into the application to which the application would use it.
I have a way for them to select the file and move it into the applications directory here:
private void SelectFile_Click(object sender, RoutedEventArgs e)
{
// Create OpenFileDialog
Microsoft.Win32.OpenFileDialog dlg = new Microsoft.Win32.OpenFileDialog();
// Set filter for file extension and default file extension
dlg.DefaultExt = ".cs";
dlg.Filter = "C# Files (*.cs)|*.cs";
// Display OpenFileDialog by calling ShowDialog method
Nullable<bool> result = dlg.ShowDialog();
// Get the selected file name and display in a TextBox
if (result == true)
{
// Open document
string filePath = dlg.FileName;
string relPath = AppDomain.CurrentDomain.BaseDirectory;
string destPath = System.IO.Path.Combine(relPath, dlg.SafeFileName);
Trace.WriteLine(destPath);
File.Move(filePath, destPath, true);
}
}
But now I run into an issue when I want to call from that file I get a error "CS0103" the file doesn't exist in the current context. So I am now unable to run the application
Is there a way around this error? so it will only run when the file exists and get rid of this error?
I have tried to check if the file exists before calling it, but the same error prevents me from running my app.
//call your order parser script
if (File.Exists("OrderParser.cs"))
{
OrderParser.OrderParser.Parser(item);
}

How to give user an options to save file in there desired location in C#?

I know how to create and save a file in C# console application but what if i want the user to choose the location of where they want to save it? i have no idea on how i can make this possible.
edit- ive realised that would be very hard to input the location the user wants to save the file to however is it possible to save the file as you would do when creating a windows word document, so the user would be able to see where they want to save the file Example
If you want a full console application, that is no windows being created, then there's only one proper thing to do: require the user to specify the save location on the command line.*
Given the fact that you have a console application, you probably already do some checking of the command line, but if not, then the command line can be read from the args argument to your Program.Main:
static void Main(string[] args)
{
...
}
There are examples on the internet to handle the command line, if you get stuck, or a new question can be asked specifically for the issue you are having.
*) Now, for the reason why this is the only proper way:
If the user needs to pass it on the command line, then the user has all the usual niceties such as tab completion available. The user can also use dir and cd before calling your program to find the proper directory.
On the other hand, if you ask the user to input it, then the user will not have tab completion, will not be able to use dir or cd, and as such will have to type it out manually all the way. Typo's or mistakes are almost guaranteed.
From a user experience point of view, this is very annoying. Programmers should therefore not ask the user to manually type out file paths during program execution. Hence, it must be specified on the command line.
Read about SaveFileDialog
private void button1_Click(object sender, System.EventArgs e)
{
Stream myStream ;
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*" ;
saveFileDialog1.FilterIndex = 2 ;
saveFileDialog1.RestoreDirectory = true ;
if(saveFileDialog1.ShowDialog() == DialogResult.OK)
{
if((myStream = saveFileDialog1.OpenFile()) != null)
{
// Code to write the stream goes here.
myStream.Close();
}
}
}
And ready to test example from msdn example
if you want to play with something like >cd (ChDir) then look at
Environment.CurrentDirectory
or/and force user to write good directory by himselft and use #Carl aswere :) but remember we leave in 21 century people are lazy
You can use the SaveFileDialog as Taumantis said but you have to add the
System.Windows.Froms
namespace and you must mark your main method as a single apartment thread
class Program
{
[STAThread]
static void Main(string[] args)
{
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
saveFileDialog1.FilterIndex = 2;
saveFileDialog1.RestoreDirectory = true;
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
}
Console.ReadKey();
}
It is not hard. You need a console to read user's input with string path = Console.ReadLine();. User will input prefered path and it will store into path variable. Now you should check if this path exits if(Directory.Exists(path)) it will return true if path exists false if path does not exist.
Code example:
Console.WriteLine("Insert a path: ");
string path = Console.ReadLine();
if(Directory.Exists(path)){
//save logic
}
else{
//path does not exist handler
}
Note: if you want to access Directory class you should use System.IO namespace.

Get full file path including file's name from an uploaded file in C#

I have this web application project which requires a better user-interface and I am doing it by C#.
I already have my html file with JS done but I need some data from user.
In my JS embedded in HTML file, I used the code below to find the file on local driver and get the data from that excel file and then put all these data into an array.
var excel = new ActiveXObject("Excel.Application");
var excel_file = excel.Workbooks.Open(file1);
var excel_sheet = excel.Worksheets("Sheet1");
However, the "file1" you see above seems to require a full name path,say "C:\test.xls" in my case.
I am new to C# and just built a button on my form design, by clicking the button, I seem to be able to browse my local file.
private void button1_Click(object sender, EventArgs e)
{
int size = -1;
DialogResult result = openFileDialog1.ShowDialog(); // Show the dialog.
if (result == DialogResult.OK) // Test result.
{
string file = openFileDialog1.FileName;
try
{
string text = File.ReadAllText(file);
size = text.Length;
}
catch (IOException)
{
}
System.Diagnostics.Process.Start(file);
}
Console.WriteLine(size); // <-- Shows file size in debugging mode.
Console.WriteLine(result); // <-- For debugging use.
}
So, my question:
How can I get this kind of full file path of an uploaded file in C# ?
And furthermore, it would be awesome if some one can tell me how to get this value into my javascript or HTML!
Thank you in advance
You won't be able to depend on getting the full path. In the end, the browser only needs to multi-part encode the physical file and submit it as a form post (of sorts). So once it has it's location and has encoded it -- it's done using it.
It's considered a security risk to expose the file structure to Javascript/HTML (ie., the internet).
Just an update.
I used another logic and it worked as expected. Instead of getting absolute file path , I managed to open the file , save it as somewhere and make my html call find that file path no matter what.

trouble saving bitmap to file in C#

I'm trying to save a bitmap to a file, all the examples and tutorials I have found suggest using this line of code to do so-
private void saveImageToolStripMenuItem_Click(object sender, EventArgs e) // Save the fractal image
{
SaveFileDialog dialog = new SaveFileDialog();
if (dialog.ShowDialog() == DialogResult.OK)
{
fractal.Save("myfile.png", ImageFormat.Png);
}
}
When I execute the code by click the save image button (which calls the above method) a save dialog appears but both the file name field and file type field are empty. I select a location to save to and give the file a name - e.g. bitmap.png then check the location and nothing has saved.
I have also checked the debug folder and nothing has appeared there ether.
I'm assuming I'm not far off or that I've made a silly mistake elsewhere any ideas or suggestions?
Assuming you are using the SaveFileDialog class, you need to set the Filter and DefaultExt properties to get the file extensions to show up.
You then read the FileName property as the argument to your Save() call

Create, write to and open a text file from SaveFileDialog

I am displaying a SaveFileDialog and when OK is clicked I am creating new file, writing some default content to it and then attempting to Open it via the OpenFile() method of the SaveFileDialog. However, the moment I call OpenFile() the content of the file are deleted.
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "XML files (*.xml)|*.xml";
saveFileDialog.RestoreDirectory = true;
if (saveFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
// First Event Creates file and writes default content to it - works ok
NewFileCreated( this, new FileCreatedEventArgs() { Template = Template.BBMF, FilePath = saveFileDialog.FileName } );
// Second Event clears file content as soon as saveFileDialog.OpenFile() called
FileLoaded( this, new FileLoadedEventArgs() { FileStream = saveFileDialog.OpenFile() } );
}
Can someone explain why this happens and what I need to be doing to successfully Open the newly created file?
According to MSDN, SaveFileDialog.OpenFile()
Caution
For security purposes, this method creates a new file with the
selected name and opens it with read/write permissions. This can cause
unintentional loss of data if you select an existing file to save to.
To save data to an existing file while retaining existing data, use
the File class to open the file using the file name returned in the
FileName property.

Categories