C# While loop not working - c#

New programmer working on a little file mover. Not sure why my while statement is not working. I am trying to have the program check if the file exists in the directory and if so, counter++ until it comes up with an original name e.g. 2018 Picture(45) and so on...
private void btnMove_Click(object sender, EventArgs e)
{
string sourcePath = #"C:\Users\David\Desktop\Personal Pictures & Videos\fromme";
string destinationPath = #"C:\Users\David\Desktop\Personal Pictures & Videos\practicefolder";
if (!Directory.Exists(destinationPath))
{
Directory.CreateDirectory(destinationPath);
}
string[] sourcefiles = Directory.GetFiles(sourcePath);
//looks at each file with its path attached.
int counter = 1;
foreach (string sourcefile in sourcefiles)
{
if (sourcefile.EndsWith(".jpeg"))
{
string destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
MessageBox.Show(destFile);
while (Directory.Exists(destFile))
{
counter++;
}
//renames and moves files from sourcePath to destinationPath
File.Move(sourcefile, destFile);

Incrementing just the counter does not automatically update the file name, which you check to exist for the break condition of the loop.
while(File.Exists(destFile))
{
counter++;
destFile = Path.Combine(destinationPath, $"2018 Picture({ counter }).jpeg");
}
We have to update the file name with the incremented counter every time.
The $ syntax for string concatenation is optional but makes the file name composition clearer.
Furthermore, Directory.Exists does not work for files. If you pass a file name that exists, it will still return false, because it checks for the directory flag on the file system entry.

Put the your code creating the filename inside the loop and the File.Move outside of the loop. You should also set an upper limit on "counter" so that you can't get stuck in an infinite loop. Then only do the File.Move if you don't hit the limit. Since you're going to be changing the name with every iteration, you should only display the messagebox after the new filename has been successfully found.
foreach (string sourcefile in sourcefiles)
{
if (sourcefile.EndsWith(".jpeg"))
{
bool bSuccess = true;
string destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
counter = 0;
while (File.Exists(destFile))
{
destFile = Path.Combine(destinationPath, "2018 Picture" + "(" + counter + ")" + ".jpeg");
counter++;
if(counter>1000)
{
MessageBox.Show("'Too many tries.' or what ever message you want to use.");
bSuccess = false;;
}
}
if(bSuccess)
{
MessageBox.Show(destFile);
File.Move(sourcefile, destFile);
}
}

I found several things to correct or improve.
private void btnMove_Click(object sender, EventArgs e)
{
string sourcePath = #"C:\Users\David\Desktop\Personal Pictures & Videos\fromme";
string destinationPath = #"C:\Users\David\Desktop\Personal Pictures & Videos\practicefolder";
//no need to check if the path exists. CreateDirectory() already does the right thing
Directory.CreateDirectory(destinationPath);
int counter = 0;
var sourcefiles = Directory.EnumerateFiles(sourcePath, "*.jpeg");
foreach (string sourcefile in sourcefiles)
{
bool tryAgain = true;
while (tryAgain)
{
try
{
counter++;
destFile = Path.Combine(destinationPath, $"2018 Picture ({ counter }).jpeg");
File.Move(sourcefile, destFile);
tryAgain = false;
MessageBox.Show(destfile);
}
catch(IOException ex)
{ //file I/O is one of the few places where exceptions might be okay for flow control
tryAgain = (counter < 10000);
}
}
}
}

Related

System.NotSupportedException: 'The specified path format is not supported.'

I have a field in a table that needs to be filled with the path and the end of the XML file to create a new file in the directory called DONE. This is made so it can tidy the directory a bit since the ones that are done don't need to be in the same directory so they are copied from one place into another.
Why is there this error?
System.NotSupportedException: 'The specified path format is not supported.'
Console.WriteLine("Ficheiro processado: " + filename);
string rootFolderPath = #"C:\XMLFiles";
string destinationPath = #"C:\XMLFiles\DONE";
string[] fileList = Directory.GetFiles(rootFolderPath);
foreach (string file1 in fileList)
{
string fileToMove = rootFolderPath + file1;
string moveTo = destinationPath + file1;
File.Move(fileToMove, moveTo);
da.SP_Insert(filename, file.Name, batch.BatchClassName, batch.Name, batch.Description, 0, "", 1, moveTo );
}
The function Directory.GetFiles(rootFolderPath); returns the full path to the file, that is filename and directory. If, like you are trying, want the filename only, you will need to extract it.
The FileInfo class is very good at extracting the Filename only of a full path.
foreach (string file1 in fileList)
{
FileInfo fi = new FileInfo(file1);
string moveTo = Path.Combine( destinationPath, fi.Name);
File.Move(file1, moveTo);
}
Rather than using string fileToMove = rootFolderPath + file1, try using System.IO.Path.Combine instead:
var fileToMove = Path.Combine(rootFolderPath, file1);
var moveTo = Path.Combine(destinationPath , file1);
GetFiles returns full paths; not just filenames:
Returns the names of files (including their paths) in the specified directory
So for the source files you don't need to combine anything, and for the target path you need to split off the filename first before combining:
foreach (string file1 in fileList)
{
string moveTo = Path.Combine(destinationPath, Path.GetFileName(file1));
File.Move(file1, moveTo);
// ...
}
This Problem was fixed this way.
using (OpenFileDialog openFileDialog1 = new OpenFileDialog())
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
string CaminhoInicial = openFileDialog1.FileName;
Guid g = Guid.NewGuid();
FileInfo fi = new FileInfo(CaminhoInicial);
File.Copy(CaminhoInicial, CaminhoFinal + g.ToString() + fi.Extension, true);
da.SP_Inserir_Imagem(id, g.ToString() + fi.Extension);
}
}
try
{
if (dt.Rows.Count != 0)
{
string NomeImagem = dt.Rows[0][0].ToString();
pictureBox1.Image = Image.FromFile(CaminhoFinal + NomeImagem.Replace(" ", ""));
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + " |||| " + ex.StackTrace, "Erro", MessageBoxButtons.OK);
}
Also read this Microfost Docs post for more context.
https://learn.microsoft.com/en-us/dotnet/api/system.io.fileinfo?view=net-5.0

C# How to copy files from one directory to another without overwriting the files in the destinaton directory? [duplicate]

My C# code is generating several text files based on input and saving those in a folder. Also, I am assuming that the name of the text file will be same as input.(The input contains only letters)
If two files has same name then it is simply overwriting the previous file.
But I want to keep both files.
I don't want to append current date time or a random number to the 2nd file name. Instead I want to do it the same way Windows does. If the fisrt file name is AAA.txt , then second file name is AAA(2).txt, third file name will be AAA(3).txt.....N th file name will be AAA(N).txt.
string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
foreach (var item in allFiles)
{
//newFileName is the txt file which is going to be saved in the provided folder
if (newFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
// What to do here ?
}
}
This will check for the existence of files with tempFileName and increment the number by one until it finds a name that does not exist in the directory.
int count = 1;
string fileNameOnly = Path.GetFileNameWithoutExtension(fullPath);
string extension = Path.GetExtension(fullPath);
string path = Path.GetDirectoryName(fullPath);
string newFullPath = fullPath;
while(File.Exists(newFullPath))
{
string tempFileName = string.Format("{0}({1})", fileNameOnly, count++);
newFullPath = Path.Combine(path, tempFileName + extension);
}
With this code if file name is "Test (3).txt" then it will become "Test (4).txt".
public static string GetUniqueFilePath(string filePath)
{
if (File.Exists(filePath))
{
string folderPath = Path.GetDirectoryName(filePath);
string fileName = Path.GetFileNameWithoutExtension(filePath);
string fileExtension = Path.GetExtension(filePath);
int number = 1;
Match regex = Regex.Match(fileName, #"^(.+) \((\d+)\)$");
if (regex.Success)
{
fileName = regex.Groups[1].Value;
number = int.Parse(regex.Groups[2].Value);
}
do
{
number++;
string newFileName = $"{fileName} ({number}){fileExtension}";
filePath = Path.Combine(folderPath, newFileName);
}
while (File.Exists(filePath));
}
return filePath;
}
The other examples don't take into account the filename / extension.
Here you go:
public static string GetUniqueFilename(string fullPath)
{
if (!Path.IsPathRooted(fullPath))
fullPath = Path.GetFullPath(fullPath);
if (File.Exists(fullPath))
{
String filename = Path.GetFileName(fullPath);
String path = fullPath.Substring(0, fullPath.Length - filename.Length);
String filenameWOExt = Path.GetFileNameWithoutExtension(fullPath);
String ext = Path.GetExtension(fullPath);
int n = 1;
do
{
fullPath = Path.Combine(path, String.Format("{0} ({1}){2}", filenameWOExt, (n++), ext));
}
while (File.Exists(fullPath));
}
return fullPath;
}
How about just:
int count = 1;
String tempFileName = newFileName;
foreach (var item in allFiles)
{
if (tempFileName.Equals(item, StringComparison.InvariantCultureIgnoreCase))
{
tempFileName = String.Format("{0}({1})", newFileName, count++);
}
}
This will use the original file name if it's not there, if not it'll take a new file name with the index in brackets (although this code isn't taking the extension into account). If the newly generated name "text(001)" is used then it'll increment until it finds a valid unused file name.
public static string AutoRenameFilename(FileInfo file)
{
var filename = file.Name.Replace(file.Extension, string.Empty);
var dir = file.Directory.FullName;
var ext = file.Extension;
if (file.Exists)
{
int count = 0;
string added;
do
{
count++;
added = "(" + count + ")";
} while (File.Exists(dir + "\\" + filename + " " + added + ext));
filename += " " + added;
}
return (dir + filename + ext);
}
int count= 0;
file is the name of file
while (File.Exists(fullpathwithfilename)) //this will check for existence of file
{
// below line names new file from file.xls to file1.xls
fullpathwithfilename= fullpathwithfilename.Replace("file.xls", "file"+count+".xls");
count++;
}
I was looking for a solution that would move a file, and make sure that if the destination file name is not already taken. It would follow the same logic as Windows and append a number, with brackets after the duplicate file.
The top answer, thanks to #cadrell0, helped me arrive to the following solution:
/// <summary>
/// Generates full file path for a file that is to be moved to a destinationFolderDir.
///
/// This method takes into account the possiblity of the file already existing,
/// and will append number surrounded with brackets to the file name.
///
/// E.g. if D:\DestinationDir contains file name file.txt,
/// and your fileToMoveFullPath is D:\Source\file.txt, the generated path will be D:\DestinationDir\file(1).txt
///
/// </summary>
/// <param name="destinationFolderDir">E.g. D:\DestinationDir </param>
/// <param name="fileToMoveFullPath">D:\Source\file.txt</param>
/// <returns></returns>
public string GetFullFilePathWithDuplicatesTakenInMind(string destinationFolderDir, string fileToMoveFullPath)
{
string destinationPathWithDuplicatesTakenInMind;
string fileNameWithExtension = Path.GetFileName(fileToMoveFullPath);
string fileNameWithoutExtension = Path.GetFileNameWithoutExtension(fileToMoveFullPath);
string fileNameExtension = Path.GetExtension(fileToMoveFullPath);
destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, fileNameWithExtension);
int count = 0;
while (File.Exists(destinationPathWithDuplicatesTakenInMind))
{
destinationPathWithDuplicatesTakenInMind = Path.Combine(destinationFolderDir, $"{fileNameWithoutExtension}({count}){fileNameExtension}");
count = count + 1; // sorry, not a fan of the ++ operator.
}
return destinationPathWithDuplicatesTakenInMind;
}
With regard to Giuseppe's comment on the way windows renames files I worked on a version that finds any existing index i.e. (2) in the file name and renames the file as per windows accordingly. The sourceFileName is assumed to be valid and the user is assumed to have write permission on the destination folder by this point:
using System.IO;
using System.Text.RegularExpressions;
private void RenameDiskFileToMSUnique(string sourceFileName)
{
string destFileName = "";
long n = 1;
// ensure the full path is qualified
if (!Path.IsPathRooted(sourceFileName)) { sourceFileName = Path.GetFullPath(sourceFileName); }
string filepath = Path.GetDirectoryName(sourceFileName);
string fileNameWOExt = Path.GetFileNameWithoutExtension(sourceFileName);
string fileNameSuffix = "";
string fileNameExt = Path.GetExtension(sourceFileName);
// if the name includes the text "(0-9)" then we have a filename, instance number and suffix
Regex r = new Regex(#"\(\d+\)");
Match match = r.Match(fileNameWOExt);
if (match.Success) // the pattern (0-9) was found
{
// text after the match
if (fileNameWOExt.Length > match.Index + match.Length) // remove the format and create the suffix
{
fileNameSuffix = fileNameWOExt.Substring(match.Index + match.Length, fileNameWOExt.Length - (match.Index + match.Length));
fileNameWOExt = fileNameWOExt.Substring(0, match.Index);
}
else // remove the format at the end
{
fileNameWOExt = fileNameWOExt.Substring(0, fileNameWOExt.Length - match.Length);
}
// increment the numeric in the name
n = Convert.ToInt64(match.Value.Substring(1, match.Length - 2)) + 1;
}
// format variation: indexed text retains the original layout, new suffixed text inserts a space!
do
{
if (match.Success) // the text was already indexed
{
if (fileNameSuffix.Length > 0)
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}{3}", fileNameWOExt, (n++), fileNameSuffix, fileNameExt));
}
else
{
destFileName = Path.Combine(filepath, String.Format("{0}({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
else // we are adding a new index
{
destFileName = Path.Combine(filepath, String.Format("{0} ({1}){2}", fileNameWOExt, (n++), fileNameExt));
}
}
while (File.Exists(destFileName));
File.Copy(sourceFileName, destFileName);
}
You can declare a Dictionary<string,int> to keep the number of times each root file name was saved. After that, on your Save method, just increase the counter and append it to the base file name:
var key = fileName.ToLower();
string newFileName;
if(!_dictionary.ContainsKey(key))
{
newFileName = fileName;
_dictionary.Add(key,0);
}
else
{
_dictionary[key]++;
newFileName = String.Format("{0}({1})", fileName, _dictionary[key])
}
This way, you'll have a counter for each distinct file name: AAA(1), AAA(2); BBB(1)...
It's working fine now. thanks guys for the answers..
string[] allFiles = Directory.GetFiles(folderPath).Select(filename => Path.GetFileNameWithoutExtension(filename)).ToArray();
string tempFileName = fileName;
int count = 1;
while (allFiles.Contains(tempFileName ))
{
tempFileName = String.Format("{0} ({1})", fileName, count++);
}
output = Path.Combine(folderPath, tempFileName );
string fullPath=output + ".xml";

How to read and update multiple files

I have 10 txt files in Debug\Tests\Text\ (10 txt files). I need to write a program to open all 10 files and updated every single file. I'm not sure how to do it. Now, I'm actually reading the folder and getting the file name and storing the file name in an array. Below is my code:
private void getFilesName()
{
string[] fileArray = Directory.GetFiles(#"Tests\Text");
//looping through the folder and get the fileNames
for (int i = 0; i<fileArray.Length; i++)
{
MessageBox.Show(fileArray[i]); // I'm doing this is to double check i manage to get the file name.
}
}
After doing this, it do read all the text file name, but the challenge now is for me to access the filename and updating every file in it. I have also created another method just for updating the values in the txt files, below is the code:
private bool modifySQLFile()
{
string destFileName = #"Tests\Text\" // I need the fileName?
string[] fileTexts = File.ReadAllLines(destFileName);
int counter = 0;
//Processing the File
foreach(string line in fileTexts)
{
//only read those non-comments line
if(line.StartsWith("--") == false)
{
//Start to replace instances of Access ID
if(line.Contains(Variable) == true)
{
fileTexts[counter] = fileTexts[counter].Replace(Variable, textBox2.Text);
}
}
counter++;
}
//check if file exists in the backup folder
if(File.Exists("Tests\\Text\\file name "+ textBox1.Text +".sql") == true)
{
MessageBox.Show("This file already exist in the backup folder");
return false;
}
else
{
//update the file
File.WriteAllLines(destFileName, fileTexts);
File.Move(destFileName, "Tests\\Text\\file name"+ textBox1.Text +".sql");
MessageBox.Show("Completed");
return true;
}
}
Your problem seems to be passing the filename variable from the loop to the method.
In order to do what you want, add a parameter to the method:
private bool ModifySQLFile(string filename)
{
string[] fileTexts = File.ReadAllLines(filename);
// ...
}
Then call the method with this parameter:
for (int i = 0; i<fileArray.Length; i++)
{
ModifySQLFile(fileArray[i]);
}
But in general you really don't want to treat a formal language as plaintext like you do. It's very easy to break the SQL like that. What if the user wanted to replace the text "insert", or replaces something with "foo'bar"?
First, implement one (file) modification:
private bool modifySQLFile(String file) {
// given source file, let´s elaborate target file name
String targetFile = Path.Combine(
Path.GetDirectoryName(file),
String.Format("{0}{1}.sql",
Path.GetFileNameWithoutExtension(file),
textBox1.Text));
// In case you want a back up
//TODO: given source file name, elaborate back up file name
//String backUpFile = Path.Combine(...);
// Check (validate) before processing: do not override existing files
if (File.Exists(targetFile))
return false;
//TODO: what if back up file exists? Should we override it? skip?
// if line doesn't start with SQL commentary --
// and contains a variable, substitute the variable with its value
var target = File
.ReadLines(file)
.Select(line => (!line.StartsWith("--") && line.Contains(Variable))
? line.Replace(Variable, textBox2.Text)
: line);
// write modified above lines into file
File.WriteAllLines(targetFile, target);
// In case you want a back up
// Move file to backup
//File.Move(file, backUpFile);
return true;
}
Then call it in the loop:
// enumerate all the text files in the directory
var files = Directory
.EnumerateFiles("#"Tests\Text", "*.txt");
//TODO: you may want filter out some files with .Where
//.Where(file => ...);
// update all the files found above
foreach (var file in files) {
if (!modifySQLFile(file))
MessageBox.Show(String.Format("{0} already exist in the backup folder", file));
}
Please, do not do:
Use Magic values: what is #"Tests\Text\" within your modifySQLFile
Mix UI MessageBox.Show(...) and logic: modifySQLFile returns true or false and it's caller who can display message box.
Materialize when it's not required (Directory.GetFiles, File.ReadAllLines)
If you would like to edit the files in parallel. With threads you can parallelize work.
for (int i = 0; i < fileArray.Length; i++)
new Thread(UpdateFileThread).Start(fileArray[i]);
private void UpdateFileThread(object path)
{
string filePath = (string)path;
//ToDo: Edit file
}
In your case you would create 10 Threads. That solution works, but is a bad pattern if you have to deal with more than 10 files.
Below i have posted the real time code ,which i have used project
protected void btnSqlfinder_Click(object sender, EventArgs e)
{
//Defining the path of directory where all files saved
string filepath = # "D:\TPMS\App_Code\";
//get the all file names inside the directory
string[] files = Directory.GetFiles(filepath);
//loop through the files to search file one by one
for (int i = 0; i < files.Length; i++)
{
string sourcefilename = files[i];
StreamReader sr = File.OpenText(sourcefilename);
string sourceline = "";
int lineno = 0;
while ((sourceline = sr.ReadLine()) != null)
{
lineno++;
//defining the Keyword for search
if (sourceline.Contains("from"))
{
//append the result to multiline text box
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("into"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("set"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
if (sourceline.Contains("delete"))
{
TxtResult.Text += sourcefilename + lineno.ToString() + sourceline + System.Environment.NewLine;
}
}
}
}
This code will fetch the multiple files in the given directory,and show the lines as per the keyword in a separate text.
But you can easily change as per your requirement,Kindly let me know your thoughts.
Thanks

Recursive Directory Structure Listing Taking To Long To Process

I am using the code below start at a path (root) provided by a GET variable and recursively go into every sub folder and display it's contents as list items. The path I'm using has about 3800 files and 375 sub folders. I takes about 45 seconds to render the page, is there any way I can cut this time down as this is unacceptable for my users.
string output;
protected void Page_Load(object sender, EventArgs e) {
getDirectoryTree(Request.QueryString["path"]);
itemWrapper.InnerHtml = output;
}
private void getDirectoryTree(string dirPath) {
try {
System.IO.DirectoryInfo rootDirectory = new System.IO.DirectoryInfo(dirPath);
foreach (System.IO.DirectoryInfo subDirectory in rootDirectory.GetDirectories()) {
output = output + "<ul><li><a>" + Regex.Replace(subDirectory.Name, "_", " ");
if (subDirectory.GetFiles().Length != 0 || subDirectory.GetDirectories().Length != 0) {
output = output + " +</a>";
} else {
output = output + "</a>";
}
getDirectoryTree(subDirectory.FullName);
if (subDirectory.GetFiles().Length != 0) {
output = output + "<ul>";
foreach (System.IO.FileInfo file in subDirectory.GetFiles()) {
output = output + "<li><a href='" + file.FullName + "'>" + file.Name + "</a></li>";
}
output = output + "</ul>";
}
output = output + "</li></ul>";
}
} catch (System.UnauthorizedAccessException) {
//This throws when we don't have access.
}
}
You should use System.Text.StringBuilder (Good performance) instead of string concatenate(Immutable) Bad performance.
You should use normal string replace function is not using complex search. subDirectory.Name.replace("_", " ");
Main reason for slowness in your code is most likely multiple calls to GetFiles and GetDirectories. You are calling them over and over again in if conditions as well as in your initial lookups. You only need the counts only once. Also, adding strings aren't helping the cause.
Following code was able to run through my simple usb-drive in 300ms and return with over 400 folders and 11000 files. On slow network drive, it was able to return in 9 seconds for 4000 files in 300 folders. It can probably be further optimized with Parallel.ForEach during recursion.
protected void Page_Load(object sender, EventArgs e) {
itemWrapper.InnerHtml = GetDirectory(Request.QueryString["path"]);
}
static string GetDirectory(string path)
{
StringBuilder output = new StringBuilder();
var subdir = System.IO.Directory.GetDirectories(path);
var files = System.IO.Directory.GetFiles(path);
output.Append("<ul><li><a>");
output.Append(path.Replace("_", " "));
output.Append(subdir.Length > 0 || files.Length > 0 ? "+</a>" : "</a>");
foreach(var sb in subdir)
{
output.Append(GetDirectory(sb));
}
if (files.Length > 0)
{
output.Append("<ul>");
foreach (var file in files)
{
output.AppendFormat("<li>{1}</li>", file, System.IO.Path.GetFileName(file));
}
output.Append("</ul>");
}
output.Append("</ul>");
return output.ToString();
}

will only copy first item in the array c#

Hi I am trying to write a simple program to copy a folder from one soure to many in parallel.
I am learning c# so have been trying to understand and change code examples, as i figured this the best way to learn somthing new.
The example below does not work as it only copies to the first destination in the destinationPaths
The stange thing is i have a simlar method to copy one file to many and this works everytime
have i missing something?? i would be greatful if someone could tell me why this is not working i am guessing that there maybe certain things you can't do in parallel
any advice would be great
public void CopyMultipleFolder(string sourceFilePath, params string[] destinationPaths)
{
if (string.IsNullOrEmpty(sourceFilePath)) MessageBox.Show("A source file must be specified.", "sourceFilePath");
else
{
if (destinationPaths == null || destinationPaths.Length == 0) MessageBox.Show("At least one destination file must be specified.", "destinationPaths");
else
{
try
{
FileIOPermission writeAccess = new FileIOPermission(FileIOPermissionAccess.AllAccess, destinationPaths);
foreach (string i in destinationPaths)
{
writeAccess.AddPathList(FileIOPermissionAccess.Write, i);
}
writeAccess.Demand();
NetworkCredential user = new NetworkCredential();
user.UserName = Properties.Settings.Default.username;
user.Password = Properties.Settings.Default.password;
if (user.Password.Length == 0 || user.UserName.Length == 0)
{
MessageBox.Show("No Username or password have been entered click username on menu bar to update", "Update Credentials");
}
else
{
Parallel.ForEach(destinationPaths, new ParallelOptions(),
destinationPath =>
{
if (sourceFilePath.EndsWith("*"))
{
int l = sourceFilePath.Length - 4;
sourceFilePath = sourceFilePath.Remove(l);
}
else
{
using (new NetworkConnection(destinationPath, user))
{
if (Directory.Exists(destinationPath + "\\" + foldername))
{
if (destinationPath.EndsWith("\\"))
{
DialogResult r = MessageBox.Show("Folder already Exists " + destinationPath + foldername + " Do You Want To overwrite All Files And Sub Folders", "Overwrite?", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath+ "\\" + foldername), true);
list = list + destinationPath + foldername + Environment.NewLine;
}
else
{
}
}
else
{
DialogResult r = MessageBox.Show("Folder already Exists " + destinationPath + "\\" + foldername + " Do you Want to overwrite All Files And SubFolders", "Overwrite?", MessageBoxButtons.YesNo);
if (r == DialogResult.Yes)
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath + "\\" + foldername), true);
list = list + destinationPath + "\\" + foldername + Environment.NewLine;
}
else
{
}
}
}
else
{
PleaseWait.Create();
foreach (string dirPath in Directory.GetDirectories(sourceFilePath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(sourceFilePath, destinationPath + "\\" + foldername));
//Copy all the files
foreach (string newPath in Directory.GetFiles(sourceFilePath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(sourceFilePath, destinationPath + "\\" + foldername), true);
list = list + destinationPath +"\\"+foldername+ Environment.NewLine;
}
}
}
PleaseWait.Destroy();
});
MessageBox.Show("Folder Has Been Copied to " + list, "Folder Copied");
}
}
catch (UnauthorizedAccessException uae)
{
MessageBox.Show(uae.ToString());
}
}
}
}
You wrote you were learning C#. So, forget about parallel execution, because it unnecessarily makes your task more complicated. Instead, start by decomposing your problem into smaller parts. The code you posted is ugly, long, repeats a lot of logic many times, and hence it is and will be hard to read, debug, and maintain.
So, start by writing small functions for individual files. You need to create a set of folders in a destination folder. Hence write a function accepting a list of names and the destination folder. You need to determine the set of folders from a source folder. So write a function which does that. The combine those two functions together. And so on.
You will end up with a much cleaner, modifiable, reusable solution. Then it will be a lot easier to plug in parallel processing. Most likely, this will be for the sake of learning it, because it makes not much sense to parallelize your problem too heavily.

Categories

Resources