How to copy specific folder to new folder by clicking a button - c#

One Question about coding (Visual Studio C# Windows form Application) There have Two folder: (Source and Target) and I build 1 button "Copy". In (Source) folder have random folders such "20190401", "20190402", "20190403", "20180401", "20170401" and "20160401". Every these folders have [10] ".txt" files. What is the coding if I only want to copy all "201904**" folders with [3] ".txt" files inside to "Target" folder?
Here my code for now, after I click a button the folder wouldn't copy. I guess there have some problem with this codes and I still not found it until. Hope you guys can help me, thank you.
*namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string FROM_DIR = "C:/Users/Desktop/Source/";
string TO_DIR = "C:/Users/Desktop/Target/";
DirectoryInfo diCopyForm = new DirectoryInfo(FROM_DIR);
DirectoryInfo[] fiDiskfiles = diCopyForm.GetDirectories();
string directname = "201904";
string filename = ".txt";
foreach (DirectoryInfo newfile in fiDiskfiles)
{
try
{
if (newfile.Name == "2019")
{
foreach (DirectoryInfo direc in newfile.GetDirectories())
if (direc.Name.StartsWith(directname))
{
int count = 0;
foreach (FileInfo file in direc.GetFiles())
{
if (file.Name.EndsWith(filename))
{
count++;
}
}
if (count == 3)
{
DirectoryCopy(direc.FullName,Path.Combine(TO_DIR,direc.Name), true);
count = 0;
MessageBox.Show("success");
}
}
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// 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);
}
// 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);
}
}
}
}
*}
By clicking the button, automatically copy all "201904**" folder and 3 ".txt files in (Source) folder to (target folder).

You didn't say which 3 txt files you want to copy so the code below copies all txt files, please explain how you select the files and I'll edit the code.
const string Source = #"C:\Users\Desktop\Source\";
const string Target = #"C:\Users\Desktop\Target\";
const string StartsWith = "201904";
const string FileType = "txt";
public static void Copy()
{
if (!Directory.Exists(Source)) //Check if the source directory exists
throw new Exception("Source directory is missing!");
Directory.CreateDirectory(Target); //If the target directory doesn't exists it will create one
var Directories = Directory.GetDirectories(Source, $"{StartsWith}*"); //Get directories which match the search pattern
for (int i = 0; i < Directories.Length; i++)
{
DirectoryInfo directory = new DirectoryInfo(Directories[i]);
Directory.CreateDirectory($"{Target}{directory.Name}"); //Create the directory in the target folder
var Files = Directory.GetFiles($"{Source}{directory.Name}", $"*.{FileType}"); //Get files
for (int j = 0; j < Files.Length; j++)
{
FileInfo file = new FileInfo(Files[j]);
File.Copy($"{Source}{directory.Name}" + #"\" + file.Name, $"{Target}{directory.Name}" + #"\" + file.Name); //Copy the file to the target folder
}
}
}
This code selects all directories which start with "201904" and all txt files inside them and copies it to the target folder.
EDIT: Fixed a mistake in the code

Related

Unzip Files With Sub-directories To Root Folder

I need some help.
I just have this code right now. This code is working, but it's not enough.
My code;
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
foreach (FileInfo currentFile in infoFile)
{
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName))
{
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
foreach (ZipEntry currentZip in zipFile)
{ currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently); }
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
I want to extract all zip files to Application.StartupPath folder from _ZipFiles folder with all subdirectories.
Here is one example;
I have one zip folder. Name: _ZipFolder
Before the unzip process;
Application.StartupPath\_ZipFiles\startProgram.zip
Application.StartupPath\_ZipFiles\updateProgram.zip
Application.StartupPath\_ZipFiles\Pack\testDownload.zip
Application.StartupPath\_ZipFiles\Pack\Version\repo2.zip
Application.StartupPath\_ZipFiles\Pack\Version\newClass.zip
Application.StartupPath\_ZipFiles\Ack\Library\argSetup.zip
Application.StartupPath\_ZipFiles\Ack\learnMachine.zip
Application.StartupPath\_ZipFiles\Code\zipVersion4.zip
After the unzip process (I exactly want to this extract);
Application.StartupPath\startProgram.exe
Application.StartupPath\updateProgram.exe
Application.StartupPath\Pack\testDownload.exe
Application.StartupPath\Pack\Version\repo2.cs
Application.StartupPath\Pack\Version\newClass.cs
Application.StartupPath\Ack\Library\argSetup.exe
Application.StartupPath\Ack\learnMachine.pdf
Application.StartupPath\Code\zipVersion4.exe
All files needs move to Application.StartupPath from _ZipFiles folder with subdirectories.
How to make this? Please help me.
I hope you understand what I want. I'm sorry for my bad English.
Remove the zip folder name from the current file directory name when extracting
Based on current example where you have _ZipFiles folder
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
var zipFolderName = #"\_ZipFiles";
foreach (FileInfo currentFile in infoFile) {
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName)) {
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
var destination = currentFile.DirectoryName.Replace(zipFolderName, "");
foreach (ZipEntry currentZip in zipFile) {
currentZip.Extract(destination, ExtractExistingFileAction.OverwriteSilently);
}
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
If I understood you correctly, you want to extract all files to Application.StartupPath directory instead in subfolders.
Try to change:
currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently);
to
currentZip.Extract(Application.StartupPath, ExtractExistingFileAction.OverwriteSilently);
If Application.StartupPath isn't suitable, then maybe use AppDomain.CurrentDomain.BaseDirectory

Use a value from a textbox in another class [duplicate]

This question already has answers here:
Copy the entire contents of a directory in C#
(28 answers)
Copy file from one directory to another
(5 answers)
Closed 5 years ago.
Okay, so I have a text box in my program where a user can enter a value, however I am wanting to call this value in another class.
public static void Main()
{
string sourceDirectory = #"F:\RootFolder\testingfolder\Test";
string targetDirectory = #"c:\targetDirectory"; //this is where the value would site
Copy(sourceDirectory, targetDirectory);
}
Not 100% sure on how to call this.
Edit
After some much needed research I have found the below to work for me;
private void CopyInstallFiles(object sender, EventArgs e)
{
string sourceDirectory = #"F:somepath";
string targetDirectory = directoryImput.Text;
//Copy all the files & Replaces any files with the same name
foreach (string newPath in System.IO.Directory.GetFiles(sourceDirectory, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceDirectory, targetDirectory), true);
I just realized that you are looking for a method to move all files and folders - silly me. Here, have some example from https://msdn.microsoft.com/en-us/library/bb762914.aspx :
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", #".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// 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);
}
// 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);
}
}
}
}
Short version - place it in DirectoryManager.cs and call by DirectoryManager.CopyDirectory(source, destination):
using System.IO;
class DirectoryManager
{
internal static void CopyDirectory(string input, string output)
{
DirectoryInfo dir = new DirectoryInfo(input);
if (dir.Exists)
{
DirectoryInfo[] dirs = dir.GetDirectories();
Directory.CreateDirectory(output);
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(output, file.Name);
file.CopyTo(temppath, false);
}
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(output, subdir.Name);
CopyDirectory(subdir.FullName, temppath);
}
}
}
}

Move multiple selected files into specific folder

I have implemented a code like this from which I got the idea somewhere.
public string BrowseFolder()
{
string filePath = string.Empty;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.Multiselect = true;
openFileDialog1.Title = "Browse EXCEL File";
openFileDialog1.Filter = "Excel Files (*.xlsx)|*.xlsx";
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
filePath = openFileDialog1.FileName;
return Path.GetDirectoryName(filePath);
}
return null;
}
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
DirectoryInfo[] dirs = dir.GetDirectories();
// If the source directory does not exist, throw an exception.
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
// If the destination directory does not exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the file contents of the directory to copy.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
// Create the path to the new copy of the file.
string temppath = Path.Combine(destDirName, file.Name.ToString());
// Copy the file.
file.CopyTo(temppath, false);
}
// If copySubDirs is true, copy the subdirectories.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
// Create the subdirectory.
string temppath = Path.Combine(destDirName, subdir.Name);
// Copy the subdirectories.
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
Ok let's assume that this two methods is in a class. I have easily understood how this codes work. It is copying all the files inside the folder I browse. This is not what I need. What I wanted to achieve is to copy only the selected files (multiple) in my folder.
I've tried to manipulate my code but I still didn't get the right solution. Thanks in advance.
foreach (string file in openFileDialog1.FileNames)
{
FileInfo fInfo = new FileInfo(file);
fInfo.MoveTo(newFilePath);
}
Ref: https://msdn.microsoft.com/en-us/library/system.windows.forms.filedialog.filenames(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.io.fileinfo.moveto(v=vs.110).aspx
You need to get all the files selected from OpenFileDialog like this:
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string[] filesSelected = openFileDialog1.FileNames;
}
The code above returns all the files that a user selected from the OpenFileDialog.

C# file backup using directory structure

I have a location like: C:\Backups
I have multiple locations such as:
C:\Users\Peter\Books
C:\ProgramData\Library
C:\Tests\Testing\Tester\
How can I copy everything in each of the locations to the backup location, so that If I drop everything in the backup location folder into C: it will overwrite all the files there with the backup? Basically how can I create the entire structure for backup.
So Far:
public void Init()
{
_locationsToBackup = new List<string>();
DataSet dataSet = _settings.Pull();// dataset is set here
DataTable settingsTable = dataSet.Tables[0];
int valueIndex = 0;
foreach (DataColumn coll in settingsTable.Columns)
{
if (coll.ColumnName == "Value")
{
break;
}
valueIndex++;
}
foreach (DataRow row in settingsTable.Rows)
{
int start = 0;
foreach (DataColumn col in settingsTable.Columns)
{
if (col.ColumnName == "SettingType")
{
string settingRowValue = row.ItemArray[start].ToString();
int settingType = Convert.ToInt32(settingRowValue);
if (settingType == 3)
{
String location = row.ItemArray[valueIndex].ToString();
AddNewLocationToBackup(location);
break;
}
}
start++;
}
}
}
public void StartBackup()
{
//make sure backup folder exists in correct location
// if not then create it.
if(!Directory.Exists(#"C:\ProgramData\Test\Backups"))
{
Directory.CreateDirectory(#"C:\ProgramData\Test\Backups");
}
foreach(string currentLocation in LocationsToBackup)
{
if (Directory.Exists(currentLocation))
{
// copy all files from currentLocation and put into backups
CopyFilesToDirWithSamePath(currentLocation, #"C:\ProgramData\Test\Backups" + #"\" + currentLocation);
}
}
}
}
public void CopyFilesToDirWithSamePath(string sourceDirInput, string targetDirInput)
{
string sourceDir = sourceDirInput;
string targetDir = targetDirInput;
foreach (var file in Directory.GetFiles(sourceDir))
{
File.Copy(file, System.IO.Path.Combine(targetDir, System.IO.Path.GetFileName(file)), true);
}
}
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(SourcePath, "*",
SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(SourcePath, DestinationPath));
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(SourcePath, "*.*",
SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(SourcePath, DestinationPath), true);
I hope this will help you
private static void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
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 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);
}
// 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);
}
}
}
I use FileSelectionManager library, take a look to this example:
http://www.fileselectionmanager.com/#Copying%20and%20moving%20files
Hope it hepls.

Error while handling multiple txt files

I'm constructing a program to search all .xml inside a folder setted by user (Source folder) and copy all these files to another folder (Destination folder).
My program is able to search all XML within all sub folders from (Source folder), the result returns around 5000 files that are placed on a list, this list is worked later by a function, but he can only work with 31 files, then appears "not responding "and the debugger shows that the program is staying a long time in the execution.
Here is my code:
Button action:
private void btnCopiarSalvar_Click(object sender, EventArgs e)
{
foreach (string name in listFileNames)
{
if (readXML(name ))
{
tbArquivo.Text = name ; //Feedback textbox, tell the current filename
}
}
pbStatus.Increment(50);
cbFinal.Checked = true; //Feedback checkBox, to tell user that the task is over.
}
Function ReadXML
public bool readXML(string name)
{
//foreach (string nome in listaArquivos)
//{ //I tried to the foreach inside, but nothing Works.
try
{
string text = null;
string readBuffer = File.ReadAllText(name);
text = readBuffer.Aggregate(text, (current, b) => current + b);
var encoding = new ASCIIEncoding();
Byte[] textobytes = encoding.GetBytes(text);
if (!File.Exists(destino))
{
string destinoComNomeArquivo = destino + "\\" + Path.GetFileName(nome);
using (FileStream fs = File.Create(destinoComNomeArquivo))
{
foreach (byte textobyte in textobytes)
{
fs.WriteByte(textobyte);
pbProcess.PerformStep();
}
Console.WriteLine("Arquivo gravado " + Path.GetFileName(nome));
}
}
pbProcess.PerformStep();
}
catch (Exception e)
{
Console.WriteLine(e);
}
//}
return true;
}
Error: ContextSwitchDeadlock was detected.
Tried Solution: Disable Managed Debug Assistants.
After disabling the MDA, the programs still only read-copy 31 files (of 5k).
The first thing i recommand is ... don't do that kind of file copy! use the File.Copy function instead.
Try to use this code snipping from MSDN:
void DoCopy(string path)
{
var copytask = new Task(() =>
{
string destinoComNomeArquivo = #"C:\" + Path.GetFileName(path);
DirectoryCopy(path, destinoComNomeArquivo, false);
});
copytask.Start();
}
private 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);
}
var counter = 0;
var maxcounter = files.Count();
while (maxcounter < counter)
{
var item = files.ElementAt(counter).Name;
WriteAsnc(item);
counter++;
}
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
const int _maxwritingprocess = Environment.ProcessorCount;
int _currentwritingtasks;
void WriteAsnc(string filepath)
{
_currentwritingtasks++;
var task = Task.Factory.StartNew(() =>
{
XDocument doc = XDocument.Load(filepath);
doc.Elements().First().Add(new XAttribute("Attribute Name","Attribute Value"));
doc.Save(filepath);
_currentwritingtasks--;
});
if(_currentwritingtasks == _maxwritingprocess)
task.Wait();
_currentwritingtasks--;
}
The next point the ContextSwitchDeadlock is a Threading problem and i thing your pbProcess is the source. What does that Process do i don't see anything of that process and i don't thing it is Impotent for your copy

Categories