looked all over and found plenty of stuff regarding this but none are using variables to form paths. What I need to do is move a folder, sub-folders and files to a new path on button click. So far none of what I found worked. At the moment, i'm getting no files or folders moved what so ever. The current solution I tried is from MSDN and tried to adapt it to my code. If you could correct the code and show me an example it would be great. I don't know what i'm doing wrong here. Here is the code:
private void CopyPartsToProject()
{
string sourcePath = (pathToQuotes + "/" + client_name.Text + "/" + quote_id.Text);
string targetPath = (pathToClient + "/" + client_name.Text + "/" + project_number.Text);
string sourceFile = sourcePath + "/" + "*.*";
string destinationFile = targetPath + "/" + "*.*";
System.IO.File.Move(sourceFile, destinationFile);
System.IO.Directory.Move(sourcePath, targetPath);
}
pathToQuotes and pathToClient are retreived from a MySQL database (from user input) in another method. The info is getting retreived without any problems and the paths are correct. If you could give me a hand it would be appreciated. Thanks.
You need a recursive method to achieve moving directories including all files and sub-directories:
private void moveDirectory(string sourcePath ,string targetPath)
{
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
String[] files = Directory.GetFiles(sourcePath);
String[] directories = Directory.GetDirectories(sourcePath);
foreach (string f in files)
{
System.IO.File.Copy(f, Path.Combine(targetPath,Path.GetFileName(f)), true);
}
foreach(string d in directories)
{
// recursive call
moveDirectory(Path.Combine(sourcePath, Path.GetFileName(d)), Path.Combine(targetPath, Path.GetFileName(d)));
}
}
then the usage is like this:
private void CopyPartsToProject()
{
string sourcePath = (pathToQuotes + "/" + client_name.Text + "/" + quote_id.Text);
string targetPath = (pathToClient + "/" + client_name.Text + "/" + project_number.Text);
moveDirectory(sourcePath, targetPath);
}
Related
In C# while moving files from source to destination folders, how to rename the destination file with prefix of directory name to each file?
static void Main(string[] args)
{
string sourceFolder = #"C:\Source";
string destinationFolder = #"C:\Destination\";
string dirName = Path.Combine(destinationFolder, DateTime.Now.ToString("dd-MM-yyyy"));
Directory.CreateDirectory(dirName);
DirectoryInfo di = new DirectoryInfo(sourceFolder);
string searchXlsPattern = "*.xls*";
try
{
//Getting list of files from Nested sub folders
ICollection<FileInfo> files = di.GetFiles(searchXlsPattern, SearchOption.AllDirectories).Where(file => !file.DirectoryName.Contains("Archive"))
.Select(x => x)
.ToList();
if (files != null && files.Count() > 0)
{
foreach (FileInfo currentfile in files)
{
if (new FileInfo(dirName + "\\" + currentfile.Name).Exists == false)
{
//Renaming old file name to new file Name
string fileDirectoryName = "";
fileDirectoryName = Path.GetDirectoryName(currentfile.FullName);
string replaceSlash = Convert.ToString(fileDirectoryName.Replace("\\", "_"));
string replaceSplChar= replaceSlash.Replace(":", "_");
string fileextension = Path.GetExtension(currentfile.Name);
string fname = currentfile.Name.Replace(fileextension, "");
string newFileName = replaceSplChar.ToString()+ "_" + fname + fileextension;
//Copy the file to destination folder
//tempfile.CopyTo(Path.Combine(destinationFolder, newFileName), true);
//Move the file to destination folder
currentfile.MoveTo(dirName + "\\" + newFileName);
////File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
//File.Move(currentfile.DirectoryName + "\\" + currentfile.Name, dirName + "\\" + newFileName);
}
}
}
else
Console.Write("There is no files in Source");
}
catch (IOException Exception)
{
Console.Write(Exception);
}
}
please help me. I would like to create new folder and save a screenshots from selenium therein.
I want, when I click the button xxx_1, folder will automatically be created with text which I enter in txt_Box1 and currently date.
Folder should be looks like that:
Test_test2_18_test3-test4_test5_test_11-Jul-2017
Here's my code
private void xxx_1(object sender, EventArgs e)
{
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)
+ "C:/xxx/xxx" + "_" + textBox1 + "_" + "xxx_xxx_xx_" + DateTime.Now;
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
//string path = #"C:\\xxx\xxx" + "_" + textBox1 + "_" + "xxx_xxx_xxx_" + DateTime.Now;
String xxx= "https://xxx.xxx.xxx";
IWebDriver driver_xx = new ChromeDriver();
driver_xx.Navigate().GoToUrl(xxx);
driver_xx.FindElement(By.Id("xxx")).SendKeys("xxx");
driver_xx.FindElement(By.Id("xx")).SendKeys("xxx");
driver_xx.FindElement(By.Id("xx")).Click();
Thread.Sleep(3000);
Screenshot ss_xx = ((ITakesScreenshot)driver_xx).GetScreenshot();
ss_xx.SaveAsFile("How to save the screenshots in new created folder??", OpenQA.Selenium.ScreenshotImageFormat.Jpeg);
}
You can't use a DateTime in your path like that as the default implementation of .ToString() on a DateTime will contain invalid characters. Use a format specifier:
string path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Desktop),
"xx\\xx",
textBox1.Text,
"xx_xxx_xxx_",
DateTime.Now.ToString("dd-MM-yyyy HH-mm-ss") // This will show '21-09-2017 16-11-15'
);
Directory.CreateDirectory(path);
Be careful that if textBox1.Text contains invalid path characters such as < > : then you'll get another exception.
Suppose i have a folder and in this folder is an image named im1.png. i want that im1.png is deleted when i save another image named im1.jpg or im1.bmp or so on...(same name but different type) in this folder. i write following code but this code just delete file that has same name and same type. Help me please...
string CopyPic(string MySourcePath, string key, string imgNum)
{
string curpath;
string newpath;
curpath = Application.Current + #"\FaceDBIMG\" + key;
if (Directory.Exists(curpath) == false)
Directory.CreateDirectory(curpath);
newpath = curpath + "\\" + imgNum + MySourcePath.Substring(MySourcePath.LastIndexOf("."));
string[] similarFiles = Directory.GetFiles(curpath, imgNum + ".*").ToArray();
foreach (var similarFile in similarFiles)
File.Delete(similarFile);
File.Copy(MySourcePath, newpath);
return newpath;
}
Here is one way to do it:
string filename = ...; //e.g. c:\directory\filename.ext
//Get the directory where the file lives
string dir = Path.GetDirectoryName(filename);
//Get the filename without the extension to use it to search the directory for similar files
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(filename);
//Search the directory for files with same name, but with any extension
//We use the Except method to remove the file it self form the search results
string[] similarFiles =
Directory.GetFiles(dir, filenameWithoutExtension + ".*")
.Except(
new []{filename},
//We should ignore the case when we remove the file itself
StringComparer.OrdinalIgnoreCase)
.ToArray();
//Delete these files
foreach(var similarFile in similarFiles)
File.Delete(similarFile);
Here is what I have tried, please note that lblImageAlt.Text property has been set to 'Images/'
string ImgPath1 = lblImageAlt1.Text.ToString();
string ImgPath2 = lblImageAlt2.Text.ToString();
string ImgPath3 = lblImageAlt3.Text.ToString();
string filename1 = "";
string filename2 = "";
string filename3 = "";
if (fileuploadimages1.HasFile)
{
if (File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while (File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
{
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
}
}
else
{
filename1 = "noImage.jpg";
}
but the same image does not get a number appended to it. What am I doing wrong here?
Path.GetFileName returns the whole filename with the extension.
Thus your code is checking if a file exists with a name like this:
image.jpg1
You should change the code to split the filename in two parts, the base filename and the extension, then check if the filename exists and then rebuild the filename from its parts adding the increment number until you find a non existant filename
// Extract just the filename from the posted file removing the path part (image.jpg)
filename1 = Path.GetFileName(fileuploadimages1.PostedFile.FileName);
baseFile = Path.GetFileNameWithoutExtension(fileuploadimages1.PostedFile.FileName);
extension = Path.GetExtension(fileuploadimages1.PostedFile.FileName);
int fileMatchCount = 1;
// Check if a file with the given name exists in the Images1 subfolder of the root folder of your site
while(File.Exists(Server.MapPath(Path.Combine(ImgPath1, filename1)))
{
// The given file exists already, so we now need to build
// a different (but related) filename using a counter....
// This will create a filename like 'image(001).jpg'
// and then we will restart the loop
fileName1 = string.Format("{0}({1:D3}){2}", baseFile, fileMatchCount, extension);
// ... but first increment the counter in case even the new name exists
fileMatchCount++;
}
// We exit the loop with a name that should not exists in the destination folder
fileuploadimages1.SaveAs(Server.MapPath(Path.Combine(ImgPath1, filename1));
You're not actually modifying filename1. You're checking if it ends in a (0), (1), etc. and incrementing your index, but never actually modifying the variable.
Try using
if(File.Exists(Server.MapPath(ImgPath1 + filename1)))
{
string extension = Path.GetExtension(filename1);
string name = Path.GetFileNameWithoutExtension(filename1);
int fileMatchCount = 1;
while(File.Exists(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension)))
fileMatchCount++;
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + name + "(" + fileMatchCount + ")" + extension));
}
else
fileuploadimages1.SaveAs(Server.MapPath(ImgPath1 + filename1));
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.