I have this code that backup and restore in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(CurrentDatabasePath);
}
I've done it! For those who are in need of the code, here it is:
using (ZipFile zip = ZipFile.Read(pathBackup))
{
zip.ExtractAll(Environment.CurrentDirectory, ExtractExistingFileAction.OverwriteSilently);
}
You cannot overwrite directly the database while you are actively using it.
By actively I mean you have an OleDbConnection open on that database.
From your code above it is not possible to understand if you are in this situation, so the first thing to do is to search for all occurences of an OleDbConnection and check if they are closed correctly. If you have a global OleDbConnection that it is kept open for the lifetime of your application (a very bad practice), then you need to close it before trying to overwrite the accdb file
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string extractedFile = Path.GetTempFileName();
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
using (ZipFile zip = ZipFile.Read(restoreFile))
{
// Extract to a temporary name built by the Framework for you....
zip.ExtractAll(extractedFile);
}
// Now, before copying over the accdb file, you need to be sure that there is no
// open OleDbConnection to this file, otherwise the IOException occurs because you
// cannot change that file while it is actively used by a OleDbConnection
// something like global_conn.Close(); global_conn.Dispose();
File.Copy(extractedFile, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
// and then reopen the connection
}
private void btn_UodateMembers_Click(object sender, EventArgs e)
{
if (!bwUpdateMembers.IsBusy)
{
bwUpdateMembers.RunWorkerAsync();
}
}
private string ExtractZip(FileInfo fi)
{
string extractTo = Path.Combine(fi.DirectoryName, Guid.NewGuid().ToString());
using (ZipFile zip = ZipFile.Read(fi.FullName))
{
foreach (ZipEntry ze in zip)
{
ze.Extract(extractTo, ExtractExistingFileAction.OverwriteSilently);
}
}
return extractTo;
}
public FileInfo GetLatestFile(DirectoryInfo di)
{
FileInfo fi = di.GetFiles()
.OrderByDescending(d => d.CreationTime)
.FirstOrDefault();
return fi;
}
private void bwUpdateMembers_DoWork(object sender, DoWorkEventArgs e)
{
string path = "C:\\Users\\Ghost Wolf\\Desktop\\zip";
DirectoryInfo di = new DirectoryInfo(path);
if (di != null)
{
FileInfo fi = GetLatestFile(di);
string folder = ExtractZip(fi);
MessageBox.Show("Your'e Files Have Been Extracted", "Notice", MessageBoxButtons.OKCancel, MessageBoxIcon.Information);
}
}
PLEASE TELL ME IF THIS WORKED FOR YOU!!
Related
I met one problem when I tried to copy file.
Error description
I worked with DataGridView and PictureBox.
Deguber of VS 2015 stopped me at
FileStream fs = File.Open(file, FileMode.Open);
in function CopyFile. I cant understand what's wrong i did.
This is some code (C#, .NET 4.5.1) from main form:
static string CopyFile(string file, string to)
{
FileInfo fileInfo = new FileInfo(file);
byte tmp = 0;
string temp = to + "\\" + fileInfo.Name;
FileStream newFile = File.Open(temp, FileMode.Create);
try
{
FileStream fs = File.Open(file, FileMode.Open);
for (int i = 0; i < fileInfo.Length; i++)
{
tmp = (byte)fs.ReadByte();
newFile.WriteByte(tmp);
}
fs.Close();
}
catch (FileNotFoundException ex)
{
MessageBox.Show("Не вдалося найти файл.");
}
newFile.Close();
return temp;
}
private void WriteNewUserToFile(User item, string pathToFile)
{
StreamWriter sw = new StreamWriter(File.Open(#pathToFile, FileMode.Append, FileAccess.Write));
sw.WriteLine(string.Format("{0}, {1}, {2}, {3}, {4}, {5}",
item.Id,
item.Image,
item.FirstName,
item.LastName,
item.Email,
item.Phone));
sw.Close();
}
private void btnAddUser_Click(object sender, EventArgs e)
{
AddUserForm dlg = new AddUserForm();
if (dlg.ShowDialog() == DialogResult.OK)
{
User item = dlg.NewUser;
item.Image = CopyFile(item.Image, "images");
WriteNewUserToFile(item, "data/users.dat");
users.Add(item);
//this.AddNewDataGridRow(item);
}
}
And some code of AddNewUserForm:
public User NewUser
{
get { return newUser; }
set { newUser = value; }
}
private void btnImage_Click(object sender, EventArgs e)
{
OpenFileDialog dlg = new OpenFileDialog();
if (dlg.ShowDialog() == DialogResult.OK)
{
txtImage.Text = dlg.FileName;
try
{
picboxImage.Image = Image.FromFile(txtImage.Text);
}
catch
{
picboxImage.Image = Image.FromFile(#"images\NoImg.bmp");
}
}
}
private void btnApply_Click(object sender, EventArgs e)
{
NewUser = new User
{
Id = Convert.ToInt32(txtId.Text),
LastName = txtLastName.Text,
FirstName = txtFirstName.Text,
Email = txtEmail.Text,
Phone = txtPhone.Text,
Image = txtImage.Text
};
this.DialogResult = DialogResult.OK;
}
If somebody need all project/code, click here (download VS project).
When you set the Image for the PictureBox using the following code, the call keeps the file handle open. So when you try to open the file again you encounter the exception.
picboxImage.Image = Image.FromFile(txtImage.Text);
According to this accepted answer, when the file handle is closed is unpredictable, in some cases, the handle won't be closed even if you explicitly close the Image.
So you may use the technique in that answer like this, to ensure the file handle is closed properly.
picboxImage.Image = Image.FromStream(new MemoryStream(File.ReadAllBytes(txtImage.Text)));
Currently having an issue when saving a merged word. doc to a specific location using a filebrowser dialog
// input destintion
private string[] sourceFiles;
private void browseButton_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowser = new FolderBrowserDialog();
diagBrowser.Description = "Select a folder which contains files needing combined...";
// Default folder, altered when the user selects folder of choice
string selectedFolder = #"";
diagBrowser.SelectedPath = selectedFolder;
// initial file path display
folderPath.Text = diagBrowser.SelectedPath;
if (DialogResult.OK == diagBrowser.ShowDialog())
{
// Grab the folder that was chosen
selectedFolder = diagBrowser.SelectedPath;
folderPath.Text = diagBrowser.SelectedPath;
sourceFiles = Directory.GetFiles(selectedFolder, "*.doc");
}
}
// output destintion
private string[] sourceFileOutput;
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
string outputFolder = #"";
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
sourceFileOutput = Directory.GetFiles(outputFolder);
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string outputFileName = (sourceFileOutput + "Combined.docx");
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
// Message displaying error.
MessageBox.Show("Please a select a relevant folder with documents to combine", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
instead of getting the 'combined.docx' in the location chosen, i instead get a file called 'System.String[]Combined' saved on the desktop. Obviously there is something clashing regarding the name and the user selected file path.
i currently have the input folder options working however the output + file name doesn't seem to be working correctly.
any suggestions or help would be greatly appreciated, thank you.
string outputFileName = (sourceFileOutput + "Combined.docx");
This should probably read
string outputFileName = selectedFolder + "Combined.docx";
That said, please use Path.Combine to combine two parts of a path.
got the program to use the 'selected' destination.
// output destintion
string outputFolder = #"";
private void browseButtonOut_Click(object sender, EventArgs e)
{
FolderBrowserDialog diagBrowserOutput = new FolderBrowserDialog();
diagBrowserOutput.Description = "Select a folder location to save the document...";
// Default folder, altered when the user selects folder of choice
diagBrowserOutput.SelectedPath = outputFolder;
// output file path display
outputPath.Text = diagBrowserOutput.SelectedPath;
if (DialogResult.OK == diagBrowserOutput.ShowDialog())
{
outputFolder = diagBrowserOutput.SelectedPath;
outputPath.Text = diagBrowserOutput.SelectedPath;
}
}
private void combineButton_Click(object sender, EventArgs e)
{
if (sourceFiles != null && sourceFiles.Length > 0)
{
string folderFolder = outputFolder;
string outputFile = "Combined.docx";
string outputFileName = Path.Combine(folderFolder, outputFile);
MsWord.Merge(sourceFiles, outputFileName, true);
// Message displaying how many files are combined.
MessageBox.Show("A total of " + sourceFiles.Length.ToString() + " documents have been merged", "Success", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
i used the path.combine as suggested, as played around with the variables i had used.
The following can scan a directory, return all files within it and save that information to a .txt file, but how and where do I write the function to get the checksum of that file next to it?
Example: C:\Desktop\E01.txt | 32DC1515AFDB7DBBEE21363D590E5CEA
I would really appreciate any help with this.
private void btnScan_Click(object sender, EventArgs e)
{
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
listBox1.Items.Clear();
string[] files = Directory.GetFiles(fbd.SelectedPath);
string[] dirs = Directory.GetDirectories(fbd.SelectedPath);
foreach (string file in files)
{
listBox1.Items.Add(file);
}
{
foreach (string dir in dirs)
{
listBox1.Items.Add(dir);
}
}
}
private void btnSave_Click(object sender, EventArgs e)
{
var saveFile = new SaveFileDialog();
saveFile.Filter = "Text (*.txt)|*.txt";
if (saveFile.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
using (var sw = new StreamWriter(saveFile.FileName, false))
foreach (var item in listBox1.Items)
sw.Write(item.ToString() + Environment.NewLine);
MessageBox.Show("This file was successfully saved.");
}
I've put together some code, to help you up. You will need to do the same for any other hash algorthim you may need.
just paste the snippet below, then add this modification:
foreach (string file in files)
{
listBox1.Items.Add(file + " | " + GetSHA1Hex(file));
}
Here you go:
public static string GetSHA1Hex(string fileName)
{
string result = string.Empty;
using (System.Security.Cryptography.SHA1 sha1 = System.Security.Cryptography.SHA1.Create("SHA1"))
using (System.IO.FileStream fs = System.IO.File.Open(fileName, System.IO.FileMode.Open))
{
byte[] b = sha1.ComputeHash(fs);
result = ToHex(b);
}
return result;
}
public static string[] HexTbl = Enumerable.Range(0, 256).Select(v => v.ToString("X2")).ToArray();
public static string ToHex(IEnumerable<byte> array)
{
System.Text.StringBuilder s = new System.Text.StringBuilder();
foreach (var v in array)
s.Append(HexTbl[v]);
return s.ToString();
}
Note I copied the ToHex from here ->
byte[] to hex string
I have this backup and restore code in C# using MS Access as its database. I finished doing the backup in zip format and now I want to restore the Zipped file. Any help will be much appreciated.
public void BackupDatabase(string dateToday)
{
string dbFileName = "dbCPS.accdb";
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory , dbFileName);
string backTimeStamp = Path.GetFileNameWithoutExtension(dbFileName) + "_" + dateToday + ".zip";// +Path.GetExtension(dbFileName);
string destFileName = backTimeStamp;// +dbFileName;
FolderBrowserDialog fbd = new FolderBrowserDialog();
if (fbd.ShowDialog() == DialogResult.OK)
{
string PathtobackUp = fbd.SelectedPath.ToString();
destFileName = Path.Combine(PathtobackUp, destFileName);
//File.Copy(CurrentDatabasePath, destFileName, true);
using (var zip = new ZipFile())
{
zip.AddFile(dbFileName);
zip.Save(destFileName);
}
MessageBox.Show("Backup successful! ");
}
}
private void backupToolStripMenuItem1_Click(object sender, EventArgs e)
{
BackupDatabase(DateTime.Now.ToString("ddMMMyyyy_HH.mm"));
}
public void RestoreDatabase(string restoreFile)
{
string dbFileName = "dbCPS.accdb";
string pathBackup = restoreFile;
string CurrentDatabasePath = Path.Combine(Environment.CurrentDirectory, dbFileName);
File.Copy(pathBackup, CurrentDatabasePath, true);
MessageBox.Show("Restore successful! ");
}
private void restoreToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
openFileDialogBackUp.FileName = "dbCPS";
openFileDialogBackUp.InitialDirectory = AppDomain.CurrentDomain.BaseDirectory + #"Sauvegardes";
if (openFileDialogBackUp.ShowDialog() == DialogResult.OK)
RestoreDatabase(openFileDialogBackUp.FileName);
}
catch (Exception error)
{
MessageBox.Show(error.ToString());
}
}
This code extracts the zipped file but I dont know how to do the restore at the same time.
using (ZipFile zip = ZipFile.Read(restoreFile))
{
zip.ExtractAll(#"C:\Users\Desktop\backup");
}
According to the MSDN documentation here, you should be able to extract the zip file directly to the destination folder. Your existing "restore" code simply does a file copy to CurrentDatabasePath, so one would expect that a statement like...
System.IO.Compression.ZipFile.ExtractToDirectory(pathToZipFile, CurrentDatabasePath);
...would be all it takes. (I would test it myself, but ZipFile was apparently added in .NET 4.5 and my copy of Visual Studio is too old.)
I am creating a file using file stream, but before that i am applying if condition to see if the file exist or not. When i click on button and if supppose file is there it deletes the file. Its ok, and again if i press the button the file gets created. At first time it works well.
Now the file is created, again if I press the button and it should delete but it is trhowing an exception saying that*The process cannot access the file 'C:\Hello1' because it is being used by another process.*
Below is my code
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
FileStream create = createFile.Create();
MessageBox.Show("Created");
}
}
So why I am not able to delete second time, My text file is not open also but still it is showing the exception.
You're never closing your stream that created the file. Put your FileStream in a using statement, which will automatically clean up the open file handle.
using(FileStream create = createFile.Create())
{
//code here
}
The file stream is still opened when you're trying second time, try this:
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
using(FileStream create = createFile.Create())
{
MessageBox.Show("Created");
}
}
}
Oh yes i got the answer,
I need to use
private void button2_Click(object sender, EventArgs e)
{
string fileName = #"C:\Hello1";
if
(File.Exists(fileName))
{
File.Delete(fileName);
MessageBox.Show("File is deleted");
}
else
{
FileInfo createFile = new FileInfo(fileName);
FileStream create = createFile.Create();
MessageBox.Show("Created");
create.Close();
}
}
We need to use create.Close();
Here is an example I used to write a local log:
StreamWriter log;
string fpath = string.Format(#"{0}\{1}.txt",GetDirectory(),DateTime.Now.ToString("yyy-MM-dd"));
if (!File.Exists(fpath))
{
log = new StreamWriter(fpath);
}
else
{
log = File.AppendText(fpath);
}
log.WriteLine(string.Format("{0} ==> {1}",DateTime.Now.ToString("MM/dd/yyy HH:mm:ss"), Message));
log.Dispose();
log = null;