I'm working on a project that will automatically update my USB with some files from my computer.
The program works on start up and monitors for any USB or CD that is plugged into the computer. My program is to then copy some folders and its files to the USB. I am having trouble copying the folders into the USB and would appreciate some help, thanks.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// this section starts the timer so it can moniter when a USB or CD is inserted into
// the computer.
//==================================================================================
private void Form1_Load(object sender, EventArgs e)
{
timer1.Interval = 100;
timer1.Start();
WindowState = FormWindowState.Minimized;
//===================================================================================
}
private void timer1_Tick(object sender, EventArgs e)
{
// this section checks to see if there is a drive type of USB and CDs.
foreach(DriveInfo drive in DriveInfo.GetDrives())
{
if (drive.DriveType == DriveType.Removable)
{
// this part is supposed to copy a folder from the PC and paste it to the USB
//==============================================================================
//==============================================================================
}
if (drive.DriveType == DriveType.CDRom)
{
// same thing but for CDs.
//==============================================================================
//==============================================================================
}
}
}
// this section opens a folderbrowserdialog that the users can use to access their folders
//and put them into a listbox so when a USB or CD is inserted it will copy those files into
// the storage devices.
//==============================================================================
private void button1_Click(object sender, EventArgs e)
{
if (folderBrowserDialog1.ShowDialog() == DialogResult.OK)
{
listBox1.Items.Add(folderBrowserDialog1.SelectedPath);
//==============================================================================
}
}
}
}
Here is how it can be done:
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Use File.Copy and use the USB drive letter for the destination. For example:
string sourceDir = #"c:\current";
string backupDir = #"f:\archives\2008";
try
{
string[] picList = Directory.GetFiles(sourceDir, "*.jpg");
string[] txtList = Directory.GetFiles(sourceDir, "*.txt");
// Copy picture files.
foreach (string f in picList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
// Use the Path.Combine method to safely append the file name to the path.
// Will overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName), true);
}
// Copy text files.
foreach (string f in txtList)
{
// Remove path from the file name.
string fName = f.Substring(sourceDir.Length + 1);
try
{
// Will not overwrite if the destination file already exists.
File.Copy(Path.Combine(sourceDir, fName), Path.Combine(backupDir, fName));
}
// Catch exception if the file was already copied.
catch (IOException copyError)
{
Console.WriteLine(copyError.Message);
}
}
// Delete source files that were copied.
foreach (string f in txtList)
{
File.Delete(f);
}
foreach (string f in picList)
{
File.Delete(f);
}
}
catch (DirectoryNotFoundException dirNotFound)
{
Console.WriteLine(dirNotFound.Message);
}
please refer to MSDN:
http://msdn.microsoft.com/en-us/library/bb762914.aspx
Related
Below is my code where I am successfully renaming only the files inside a a folder and also crawls inside every subfolders and renames the entire .png files.
I am trying to add a customization where if the file name already got #1 or #5 or any #(number) then i want the conversation to skip that file and go to next file
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderDlg = new FolderBrowserDialog();
//folderDlg.ShowDialog();
if (folderDlg.ShowDialog() != DialogResult.OK)
{
return;
}
// Has different framework dependend implementations
// in order to handle unauthorized access to subfolders
RenameAllPngFiles(folderDlg.SelectedPath);
}
private void RenameAllPngFiles(string directoryPath)
{
RenameCurrentPng(directoryPath);
foreach (var item in GetDirectoryInfos(directoryPath))
{
RenameCurrentPng(item.FullName);
}
}
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
// The new file name without path
var newFileName = $"{System.IO.Path.GetFileNameWithoutExtension(originalFullFileName)}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
private DirectoryInfo[] GetDirectoryInfos(string directoryPath)
{
DirectoryInfo di = new DirectoryInfo(directoryPath);
DirectoryInfo[] directories = di.GetDirectories("*", System.IO.SearchOption.AllDirectories);
return directories;
}
Just use the String.Contains method to check for #.
private void RenameCurrentPng(string directoryPath)
{
int fileNameSuffixCounter = 1;
foreach (string originalFullFileName in Directory.EnumerateFiles(directoryPath, "*.png"))
{
string ShortFileName = System.IO.Path.GetFileNameWithoutExtension(originalFullFileName);
if (!ShortFileName.Contains("#"))
{
// The new file name without path
var newFileName = $"{ShortFileName}#{fileNameSuffixCounter++}{System.IO.Path.GetExtension(originalFullFileName)}";
FileSystem.RenameFile(originalFullFileName, newFileName);
}
}
}
This question already has answers here:
Visual feedback on long running task
(1 answer)
C# WinForm progress bar not progressively increasing
(3 answers)
Closed 3 years ago.
I have a piece of code wich copies a folder to another directory. I wanted to implement a progress bar so the user can see the progress of the files being copied. I've tried some things, but I just cant get it to work.
This is the code I thought would do what I said above, but the progress bar doesn't make any progress, why the folder is actually being copied.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace intChanger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
}
string Dirr;
string Dirr2;
int no = 0;
int Count = 0;
int Count2 = 0;
private void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
progressBar1.Value = Count2 * Count;
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void button1_Click(object sender, EventArgs e)
{
DirectoryCopy(#"C:\Users\Stefan\Downloads\Portable Python 2.7.15 Basic (x64)\Portable Python 2.7.15 x64", #"C:\Users\Stefan\Documents\Backuppers_Backups\Portable Python 2.7.15 x64", true);
MessageBox.Show("Done coppieng", "Done", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
}
}
I expect the Progress bar to go slowly up, but it doesn't: It stays at 0
However it does actually copy the files
You should put the copy process in a BackgroundWorker and refresh the progress bar from the _bgwCopyOperation_ProgressChanged event.
Because you are processing the copy operation in the GUI thread, you block controls from refreshing.
Try something like this. You still need to modify this a bit to pass the parameters to the _bgwCopyOperation_DoWork event.
private void _bgwCopyOperation_DoWork(object sender, DoWorkEventArgs e)
{
if (no == 0)
{
no = 1;
Dirr = sourceDirName;
Dirr2 = destDirName;
Count = Directory.GetFiles(Dirr, "*.*", SearchOption.AllDirectories).Length;
Count = 100 / Count;
}
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
Count2 = Count2 + 1;
//Update progressbar here
_bgwCopyOperation.ReportProgress(Count2 * Count);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
private void _bgwCopyOperation_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
The BackgroundWorker is certainly the best approach, it will send all the heavy copy into a separate thread an not keep the GUI thread busy with simple copy.
...but if you are copying small folders, you could try using the Refresh function on the progress bar:
using System;
using System.Threading;
using System.Windows.Forms;
namespace ProgressBat
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
button1.Enabled = false;
progressBar1.Value = 0;
for (int i = 0; i < 100; i++)
{
progressBar1.Value = i;
progressBar1.Refresh();
Thread.Sleep(50);
}
button1.Enabled = true;
}
}
}
That example will get the progress bar moving correctly.
And it is a one line fix to your code
I'm trying to make a windows form application to do the same thing that I have a console application doing. The design is just a box with two labels (going to try to add a progress bar later on) but for some reason the code is not working correctly.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Diagnostics;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void label1_Click(object sender, EventArgs e)
{
}
private void Form1_Load(object sender, EventArgs e)
{
string date = DateTime.Now.ToString("ddMMyy");
string Source = #"G:\Personal\A1";
string Destination = #"D:\_Lil USB Backup\" + "b";
if (System.IO.Directory.Exists(Source))
{
if (System.IO.Directory.Exists(Destination))
{
infoBox.Text = "Backup already exists for today. U rem";
}
else
{
System.IO.Directory.CreateDirectory(Destination);
}
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
}
else
{
infoBox.Text = "Source does not exist, try plugging the USB in dipshit.";
}
}
private static void CopyAllFiles(string Source, string Destination)
{
try
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(Source);
DirectoryInfo[] dirs = dir.GetDirectories();
if (!dir.Exists)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Directory could not be found.";
}
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(Destination))
{
Directory.CreateDirectory(Destination);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(Destination, file.Name);
file.CopyTo(temppath, true);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(Destination, subdir.Name);
CopyAllFiles(subdir.FullName, temppath);
}
}
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
}
private void progressBar1_Click(object sender, EventArgs e)
{
}
}
}
The problem is that it outputs the text in the labels as expected as if it was successful. Yet it does not create a new folder or copy any of the files. I have no idea why and it's not giving me any errors!
First of all you catch exception within CopyAllFiles method. And its code
catch (Exception ex)
{
Label infoBoxErr = new Label();
infoBoxErr.Text = "Oh. Something didn't work, sorry. Might have been this: " + ex.Message + " lol!";
}
doesn't do anything because it creates label infoBoxErr in memory and doesn't display it at all.
So, the following code
try
{
CopyAllFiles(Source, Destination);
infoBox.Text = "Files backed up successfully.";
if (System.IO.Directory.Exists(#"D:\" + date + #"System Volume Information"))
{
Directory.Delete(#"D:\" + date + #"System Volume Information", true);
infoBox.Text = "Files backed up successfully.\n System Volume Information folder deleted.\n Backup successfull.";
}
else
{
infoBox.Text = "System Volume Information folder does not exist and therefore was not deleted.\n Backup successfull.";
}
}
catch (Exception ez)
{
infoBox.Text = "Umm, something didn't work. Oh maybe it was this? " + ez.Message;
}
never reaches the catch block (because of inner catch in CopyAllFiles method) and just displays success text.
So I'd suggest you to remove that inner catch and see what happens.
Hey guys so I'm working on a small program which sorta speeds up your pc, but I have a problem I get an exception if I try to delete files, I believe cause they are in use. Though it deletes some, but not much. My question is how to delete files in use, and how to delete sub folders inside the folder
//this is my directory:
DirectoryInfo tempPath = new DirectoryInfo(#"C:\Users\" + Environment.UserName + #"\AppData\Local\Temp");
private void button8_Click(object sender, EventArgs e)
{
if (checkBox5.Checked)
{
//loop through these files
foreach (FileInfo file in tempPath.GetFiles())
{
//delete files in content
file.Delete();
}
}
}
You must delete Folder recursivly with set FileAttributes normal.
private static void DeleteAllFolderRecursive(DirectoryInfo yourBaseDir)
{
baseDir.Attributes = FileAttributes.Normal;
foreach (var childDir in baseDir.GetDirectories())
DeleteFolderRecursive(childDir);
foreach (var file in baseDir.GetFiles())
file.IsReadOnly = false;
baseDir.Delete(true);
}
And you call this :
DirectoryInfo tempPath = new DirectoryInfo(#"C:\Users\" + Environment.UserName + #"\AppData\Local\Temp");
DeleteAllFolderRecursive(tempPath);
The problem is that when copying the files in the netscan.zip file to the usb.
It unzip all to root.
This is how the files looks in KHtemp folder:
c:\Data\install\ <- Files
c:\Data\info <- Files
c:\Knowhow.exe
But when the copying is done i looks like this on the usb
\knohow.exe
\data\
\intall\
\info\
I can not find out what iam doing wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.IO.Compression;
using System.Linq;
using System.Net;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace KHupdater
{
public partial class Install : Form
{
public Install()
{
InitializeComponent();
Close.Visible = false;
}
// COPY
#region copy
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach (var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach (var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, sourceSubPath.Substring(sourcePath.Length));
CopyFolder(sourceSubPath, destPath);
}
}
#endregion
private void Start_Click(object sender, EventArgs e)
{
Start.Visible = false;
Loadingbar.Visible = true;
string tempfolder = "C:\\KHtemp";
string tempfile = #"c:\KHtemp\Update.zip";
// If the 'tempfolder' exists it will be deleted
if (Directory.Exists(tempfolder))
{
Directory.Delete("c:\\KHtemp", true);
}
Loadingbar.Value = (10);
// Make Folder and download file
if (!Directory.Exists(tempfolder))
{
Directory.CreateDirectory(tempfolder);
}
WebClient webClient = new WebClient();
webClient.DownloadFile("http://67.327.195.57/netscan.zip", #"c:\KHtemp\Update.zip");
Loadingbar.Value = (50);
// Unrar files in to 'tempfolder'
ZipFile.ExtractToDirectory(tempfile, tempfolder);
// Del rar file from 'tempfolder'
File.Delete("c:\\KHtemp\\Update.zip");
// !?
Loadingbar.Value = (70);
// Copy files to USB
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
// Copy All files from 'tempfolder' to root of the USB
foreach (var sourceFilePath in Directory.GetFiles(tempfolder))
{
string fileName = Path.GetFileName(sourceFilePath);
string destinationFilePath = Path.Combine(root, fileName);
System.IO.File.Copy(sourceFilePath, destinationFilePath, true);
CopyFolder(tempfolder, root);
}
Loadingbar.Value = (90);
//// Del 'tempfolder'
Directory.Delete("c:\\KHtemp", true);
////
this.Loadingbar.Style = System.Windows.Forms.ProgressBarStyle.Blocks;
// Show message when done
Loadingbar.Value = (100);
label1.Text = "Update is Done";
Close.Visible = true;
}
private void Close_Click(object sender, EventArgs e)
{
var StartupPath = Application.StartupPath;
var root = System.IO.Path.GetPathRoot(StartupPath);
var Knowhowfile = "Knowhow.exe";
var Knowhow = Process.Start(root + Knowhowfile);
Environment.Exit(1);
}
}
}
You need to copy each folder as well - something like this will work:
public static void CopyFolder(string sourcePath, string destinationPath)
{
Directory.CreateDirectory(destinationPath);
// Copy files first.
foreach(var sourceFile in Directory.GetFiles(sourcePath))
{
string destFile = Path.Combine(destinationPath, Path.GetFileName(sourceFile));
File.Copy(sourceFile, destFile, true);
}
foreach(var sourceSubPath in Directory.GetDirectories(sourcePath))
{
string destPath = Path.Combine(destinationPath, Path.GetFileName(sourceSubPath));
CopyFolder(sourceSubPath, destPath);
}
}
You should call CopyFolder(tempFolder, root)
Please note that it is not tested, you need to debug the CopyFolder method to verify e.g. destPath
You need to identify the current item in loop is File or Directory.
If it's a file then write a code of copy and if it's a directory then create it manually by using System.IO.Directory.CreateDirectory("");