Why is File.Move not working as expected? - c#

I am trying to move all files from rootFolderPath to destinationPath
try
{
string rootFolderPath = #"D:\Log_siteq\";
if (!Directory.Exists(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString())))
{
System.IO.Directory.CreateDirectory(Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString()));
}
string destinationPath = Path.Combine(#"D:\Log_takaya\" + comboBox1.SelectedItem.ToString() );
string fileTypes = #"*.*";
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, fileTypes);
foreach (string file in fileList)
{
string ext = Path.GetExtension(file);
string destination = Path.Combine(destinationPath,file);
File.Move( file,destination);
MessageBox.Show(file);
MessageBox.Show(destination);
}
}
catch(Exception ex)
{
MessageBox.Show(ex.ToString());
}
Apparently MessageBox.Show(file); shows me my root folder path ( as is normal) but MessageBox.Show(destination); is showing me the same thing.
What gives? It just moves my file from my root folder in the same folder.Am I not getting something?

You are combining the destinationPath with the complete file path of file:
string destination = Path.Combine(destinationPath, file);
which will just overwrite the destination with the original file path (because "C:\desitnation\C:\source\filename.txt" isn't a valid path).
Instead, you need only the file name like this:
string destination = Path.Combine(destinationPath, Path.GetFileName(file));

Related

ziparchive text files in c#

I have a folder full of text files. I want to zip each one individually. If there are First.txt and Second.txt in the folder C:\Temp\raw
I want to zip First.txt as First.zip and move it to C:\Temp\Done and Second.txt zipped as Second.zip and move it to C:\Temp\Done. This is the code I have
-- SourcePath = C:\Temp\raw tempPath = C:\temp\Done in app.config
public static DirectoryInfo sourcePath = new DirectoryInfo(ConfigurationManager.AppSettings["sourcePath"].ToString());
public static string tempPath = ConfigurationManager.AppSettings["tempPath"].ToString();
var files = System.IO.Directory.GetFiles(sourcePath.ToString(), "*.txt").OrderBy(f => f);
string zipfilename = "";
try
{
foreach (var fPath in files)
{
string fileNameNoPath = Path.GetFileName(fPath);
string destFile = Path.Combine(tempPath, fileNameNoPath);
System.IO.File.Move(fPath, destFile);
ZipFile.CreateFromDirectory(tempPath, tempPath, CompressionLevel.Fastest, true);
}
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
I am getting errors. System.UnauthorizedAccessException: Access to the path 'C:\Temp\Done' is denied
I do have access to C:\temp\folder and I am running as admin
Can someone guide me
Thanks
MR

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

Extract zip file and overwrite (in the same directory - C#)

I'm starting some C# stuff, and i would like to extract and force to overwrite all files from a zip archive. I know that there are many other solution in Stack, but nothing works for me :/
i've tried this method:
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, extractPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
This extractor works fine, but doesn't allow me to overwrite files meanwhile extraction, and it returns error and exceptions ... i've tried to take a look at MS-Documention, without success ...
someone know how does it work ?
Try something like this. Away from my dev box so this may require some tweaking, just writing it from memory.
Edit: As someone mentioned you can use ExtractToFile which has an overwrite option. ExtractToDirectory does not.
Essentially you unzip to a temporary folder then check if an unzipped file's name already exists in the destination folder. If so, it deletes the existing file and moves the newly unzipped one to the destination folder.
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped files
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
//Delete the temporary directory.
Directory.Delete(tempPath);
return (0); // 0 all fine
}
catch (Exception)
{
return (1); // 1 = extract error
}
Edit, in the event directories are unzipped (again, may need to be tweaked, I didn't test it):
try
{
string zipPath = (Directory.GetCurrentDirectory() + "\\" + "my_zip");
Console.WriteLine("Zip's path: " + zipPath);
//Declare a temporary path to unzip your files
string tempPath = Path.Combine(Directory.GetCurrentDirectory(), "tempUnzip");
string extractPath = Directory.GetCurrentDirectory();
ZipFile.ExtractToDirectory(zipPath, tempPath);
//build an array of the unzipped directories:
string[] folders = Directory.GetDirectories(tempPath);
foreach (string folder in folders)
{
DirectoryInfo d = new DirectoryInfo(folder);
//If the directory doesn't already exist in the destination folder, move it to the destination.
if (!Directory.Exists(Path.Combine(extractPath,d.Name)))
{
Directory.Move(d.FullName, Path.Combine(extractPath, d.Name));
continue;
}
//If directory does exist, iterate through the files updating duplicates.
else
{
string[] subFiles = Directory.GetFiles(d.FullName);
foreach (string subFile in subFiles)
{
FileInfo f = new FileInfo(subFile);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath, d.Name, f.Name)))
{
File.Delete(Path.Combine(extractPath, d.Name, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, d.Name, f.Name));
}
}
}
}
//build an array of the unzipped files in the parent directory
string[] files = Directory.GetFiles(tempPath);
foreach (string file in files)
{
FileInfo f = new FileInfo(file);
//Check if the file exists already, if so delete it and then move the new file to the extract folder
if (File.Exists(Path.Combine(extractPath,f.Name)))
{
File.Delete(Path.Combine(extractPath, f.Name));
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
else
{
File.Move(f.FullName, Path.Combine(extractPath, f.Name));
}
}
Directory.Delete(tempPath);
return (0); // 0 all fine
}

How to create a same directory as source copying a file in c#

I am copying file from my server.map path to some folder in C:\ But When i am copying my file i want that it create the folder path same it is in server.map path with file to copy
Here is my code where i am copying file but it is not creating the same directory which i want.
public void CopyFiles()
{
string Filename = "PSK_20150318_1143342198885.jpg";
string sourcePath = Server.MapPath("~/UserFiles/Images/croppedAvatar/");
string targetPath = #"C:\MyCopyFIle\";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath,Filename);
string destFile = System.IO.Path.Combine(targetPath,Filename);
// To copy a folder's contents to a new location:
// Create a new target folder, if necessary.
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
// To copy a file to another location and
// overwrite the destination file if it already exists.
System.IO.File.Copy(sourceFile, destFile, true);
// To copy all the files in one directory to another directory.
// Get the files in the source folder. (To recursively iterate through
// all subfolders under the current directory, see
// "How to: Iterate Through a Directory Tree.")
// Note: Check for target path was performed previously
// in this code example.
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
// Use static Path methods to extract only the file name from the path.
Filename = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath);
System.IO.File.Copy(s, destFile, true);
}
}
else
{
Debug.WriteLine("Source path does not exist!");
}
}
Now the source path contain /userfiles/images/croppedavatar directory in it when I am copying it in c:\MyCopyFile I want it create a folder structure like c:\MyCopyFile\UserFile\Images\CroppedAvatar
you have to check each file structure and create the same on destination and then copy file as
public void CopyFiles(string srcpath, List<string> sourcefiles, string destpath)
{
DirectoryInfo dsourceinfo = new DirectoryInfo(srcpath);
if (!Directory.Exists(destpath))
{
Directory.CreateDirectory(destpath);
}
DirectoryInfo dtargetinfo = new DirectoryInfo(destpath);
List<FileInfo> fileinfo = sourcefiles.Select(s => new FileInfo(s)).ToList();
foreach (var item in fileinfo)
{
string destNewPath = CreateDirectoryStructure(item.Directory.FullName, destpath) + "\\" + item.Name;
File.Copy(item.FullName, destNewPath);
}
}
public string CreateDirectoryStructure(string newPath, string destPath)
{
Queue<string> queue = new Queue<string>(newPath.Split(new string[] { "\\" }, StringSplitOptions.RemoveEmptyEntries));
queue.Dequeue();
while (queue.Count>0)
{
string dirName = queue.Dequeue();
if(!new DirectoryInfo(destPath).GetDirectories().Any(a=>a.Name==dirName))
{
Directory.CreateDirectory(destPath + "\\" + dirName);
destPath += "\\" + dirName;
}
}
return destPath;
}
You can simply create a folder structure using FileInfo Class:
string path=#"c:/MyCopyFile/UserFile/Images/CroppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
This will create a directory where you can copy what you want to.
You can change your code like following
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
// Copy the files and overwrite destination files if they already exist.
foreach (string s in files)
{
Filename = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, Filename);
string path = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/";
FileInfo file = new FileInfo(path);
file.Directory.Create();
string folderStructurePath = #"C:/MyCopyFile/UserFiles/Images/croppedAvatar/" + Filename;
System.IO.File.Copy(sourceFile, folderStructurePath, true);
}
}

Could not find a part of the path

I am getting " Could not find a part of the path" error while copying a file from server to local machine. here is my code sample:
try
{
string serverfile = #"E:\installer.msi";
string localFile = Path.GetTempPath();
FileInfo fileInfo = new FileInfo(serverfile);
fileInfo.CopyTo(localFile);
return true;
}
catch (Exception ex)
{
return false;
}
Can anyone tell me what's wrong with my code.
Path.GetTempPath
is returning you folder path. you need to specify file path as well. You can do it like this
string tempPath = Path.GetTempPath();
string serverfile = #"E:\installer.msi";
string path = Path.Combine(tempPath, Path.GetFileName(serverfile));
File.Copy(serverfile, path); //you can use the overload to specify do you want to overwrite or not
You should copy file to file, not file to directory:
...
string serverfile = #"E:\installer.msi";
string localFile = Path.GetTempPath();
FileInfo fileInfo = new FileInfo(serverfile);
// Copy to localFile (which is TempPath) + installer.msi
fileInfo.CopyTo(Path.Combine(localFile, Path.GetFileName(serverfile)));
...

Categories

Resources