I have two folders as part of my project, in the folder "Images" is a file called "FingerprintScan.jpg". What I am trying to do is fetch this file and then save it in my other folder called "FingerPrints".
The code I am using does not throw any errors and as far as I can tell should logically work however nothing happens.
string fileName = "FingerprintScan.JPG";
string newfilename = TextBoxUsername.Text + LabelStudentID.Text + ".JPG";
string appPath1 = AppDomain.CurrentDomain.BaseDirectory + #"Images\";
string appPath2 = AppDomain.CurrentDomain.BaseDirectory + #"FingerPrints\";
string sourceFile = System.IO.Path.Combine(appPath1, fileName);
string destFile = System.IO.Path.Combine(appPath2, newfilename);
System.IO.File.Copy(sourceFile, destFile, true);
I have tried playing around and using #"~\Images\ and #"Images but had no luck.
Try this combination and make sure your directory name and source file name match with the physical directory and file
string appPath1 = AppDomain.CurrentDomain.BaseDirectory + "Images";
string appPath2 = AppDomain.CurrentDomain.BaseDirectory + "FingerPrints";
Guys I am trying to move all files ending with _DONE into another folder.
I tried
//take all files of main folder to folder model_RCCMrecTransfered
string rootFolderPath = #"F:/model_RCCMREC/";
string destinationPath = #"F:/model_RCCMrecTransfered/";
string filesToDelete = #"*_DONE.wav"; // Only delete WAV files ending by "_DONE" in their filenames
string[] fileList = System.IO.Directory.GetFiles(rootFolderPath, filesToDelete);
foreach (string file in fileList)
{
string fileToMove = rootFolderPath + file;
string moveTo = destinationPath + file;
//moving file
File.Move(fileToMove, moveTo);
But on executing these codes i get an error saying.
The given path's format is not supported.
Where did I go wrong ?
Your slashes are in the wrong direction. On windows you should use back slashes. E.g.
string rootFolderPath = #"F:\model_RCCMREC\";
string destinationPath = #"F:\model_RCCMrecTransfered\";
I made it this way:
if (Directory.Exists(directoryPath))
{
foreach (var file in new DirectoryInfo(directoryPath).GetFiles())
{
file.MoveTo($#"{newDirectoryPath}\{file.Name}");
}
}
file is a type of FileInfo class. It already has a Method called MoveTo() that takes a destination path.
The array of file names returned from System.IO.Directory.GetFiles() includes their full path. (See http://msdn.microsoft.com/en-us/library/07wt70x2.aspx) This means that appending the source and destination directories to the file value isn't going to be what you expect. You'll end up with values like F:\model_RCCMREC\F:\model_RCCMREC\something_DONE.wav in fileToMove. If you set a breakpoint on the File.Move() line, you could look at the values you are passing, which can help debug a situation like this.
Briefly, you'll need to determine the relative path from rootFolderPath to each file in order to determine the proper destination path. Take a look at the System.IO.Path class (http://msdn.microsoft.com/en-us/library/system.io.path.aspx) for methods that will help. (In particular, you should consider Path.Combine() rather than + for building paths.)
Please try the below function. This works fine.
Function:
public static void DirectoryCopy(string strSource, string Copy_dest)
{
DirectoryInfo dirInfo = new DirectoryInfo(strSource);
DirectoryInfo[] directories = dirInfo.GetDirectories();
FileInfo[] files = dirInfo.GetFiles();
foreach (DirectoryInfo tempdir in directories)
{
Console.WriteLine(strSource + "/" +tempdir);
Directory.CreateDirectory(Copy_dest + "/" + tempdir.Name);// creating the Directory
var ext = System.IO.Path.GetExtension(tempdir.Name);
if (System.IO.Path.HasExtension(ext))
{
foreach (FileInfo tempfile in files)
{
tempfile.CopyTo(Path.Combine(strSource + "/" + tempfile.Name, Copy_dest + "/" + tempfile.Name));
}
}
DirectoryCopy(strSource + "/" + tempdir.Name, Copy_dest + "/" + tempdir.Name);
}
FileInfo[] files1 = dirInfo.GetFiles();
foreach (FileInfo tempfile in files1)
{
tempfile.CopyTo(Path.Combine(Copy_dest, tempfile.Name));
}
}
string str = "C:\\efe.txt";
string dir = "D:\\";
I want to move or copy "efe.txt" file under "D:\" directory. How can I do that.
thanks for your advice.....
As others have mentioned you want to use File.Move, but given your input you'll also want to use Path.Combine and Path.GetFileName like so
string str = "C:\\efe.txt";
string dir = "D:\\";
File.Move(str, Path.Combine(dir, Path.GetFileName(str)));
From MSDN: How to: Copy, Delete, and Move Files and Folders (C# Programming Guide):
// Simple synchronous file move operations with no user interface.
public class SimpleFileMove
{
static void Main()
{
string sourceFile = #"C:\Users\Public\public\test.txt";
string destinationFile = #"C:\Users\Public\private\test.txt";
// To move a file or folder to a new location:
System.IO.File.Move(sourceFile, destinationFile);
// To move an entire directory. To programmatically modify or combine
// path strings, use the System.IO.Path class.
System.IO.Directory.Move(#"C:\Users\Public\public\test\", #"C:\Users\Public\private");
}
}
Try File.Move
using System.IO;
...
string src = "C:\\efe.txt";
string dest = "D:\\efe.txt";
File.Move(src, dest);
I have an issue with the reading a file in C#
I have two different locations for .exe (both different) and reading the same .xml file. So when I give the path like this:
TextReader textReader = new StreamReader(#"../../../TrajectoryGen/obstacleList.xml");
it is able to read from one location ( which is 3 folders behind as used in the path) but not from another location (which is only 2 folders behind)
How do I fix this problem so that it works from both folders?
First way, this relies on you knowing one of the parent folder's names.
const string FILENAME = "obstacleList.xml";
const string FOLDER = "TrajectoryGen";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
do
{
path = Path.GetDirectoryName(path);
} while (!Path.GetFileName(path).Equals(FOLDER, StringComparison.OrdinalIgnoreCase));
string filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
^^ You can also use a partial path in the FILENAME like the example below incase you need to into directories once you are at your "base" folder that you know the name of.
Second way blindly continues up directories
const string FILENAME = #"TrajectoryGen\obstacleList.xml";
string path = Path.GetFullPath(System.Reflection.Assembly.GetExecutingAssembly().Location);
string filepath;
do
{
path = Path.GetDirectoryName(path);
//pump
filepath = String.Format("{0}{1}{2}", path, Path.DirectorySeparatorChar, FILENAME);
} while (!File.Exists(filepath));
Both require "using System.IO;" and both have no error handling implemented and will throw NullReferenceException if the file/folder is not found.
I purposely used the do-while loop because the definition of path will included the executable name.
Sometimes, in my app, I would like to create a copy of a file that already exist, but I don't want to test if the file already exist, I want only that a copy of that file be created, like Windows 7 do.
E.g.: A file tips.txt. When my app copy it, another file will be created named tips - copy.txt. After, if necessary, a "copy of a copy" tips - copy - copy.txt.
Is there something that I can do in this situation?
Obs: in this app, I am using .NET 3.5 and WPF.
Obs2: I made this question because I thought already existed something similar in .NET.
You should extract the filename and the extension then do a simple File.Copy with a new formatted name
string fileName = "tips.txt";
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
File.Copy(fileName, string.Format("{0} - Copy{1}", file, ext);
things get a bit more complicated if you have a fullpath to copy from
string fileName = "C:\\test\\tips.txt";
string path = Path.GetDirectoryName(fileName);
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
File.Copy(fileName, Path.Combine(path, string.Format("{0} - Copy{1}", file, ext));
but if you really want to mimic the behavior of Windows Explorer we should do:
string fileName = "C:\\test\\tips.txt";
string path = Path.GetDirectoryName(fileName);
string file = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
if(file.EndsWith(" - Copy")) file = file.Remove(0, file.Length - 7);
string destFile = Path.Combine(path, string.Format("{0} - Copy{1}", file, ext));
int num = 2;
while(File.Exists(destFile))
{
destFile = Path.Combine(path, string.Format("{0} - Copy ({1}){2}", file, num, ext));
num++;
}
File.Copy(fileName, destFile);
If Windows Explorer copies a file that ends with " - Copy", it adds a progressive number to destination file, not another " - Copy".
You should also consider that the string 'Copy' is localized and thus it changes in non-english version of the operating system.
In addition to other answers suggesting the usage of classes in the System.IO namespace if you want to get the exact same semantics as Windows Copy dialog, you could use the IFileOperation COM object. And here's a managed wrapper for it.
Not sure if this is exactly what you mean, but:
string fileName = "tips.txt";
File.Copy(fileName, string.format("{0} - copy", fileName);
Or:
File.Copy(fileName, string.format("{0} - copy{1}",
Path.GetFileNameWithoutExtension(fileName),
Path.GetExtension(fileName));
You can use File.Copy
http://msdn.microsoft.com/en-us/library/9706cfs5.aspx
What about :
public static void CopyFileLikeWin7(string pathIn,string fileName, string pathOut)
{
string potentialFileName = Path.Combine(pathOut,fileName);
if(File.Exists(potentialFileName))
{
CopyFileLikeWin7(pathIn, Path.GetFileNameWithoutExtension(fileName) + "-copy" + Path.GetExtension(fileName), pathOut);
}
else
{
File.Copy(pathIn,potentialFileName);
}
}
How about
string fileName = "tips.txt";
string filenamewithoutext = Path.GetFileNameWithoutExtension(fileName);
string ext = Path.GetExtension(fileName);
File.Copy(fileName, string.format("{0} - Copy{1}", filenamewithoutext, ext);
Ok, do not test. Just copy the file and don't handle exception
try
{
File.Copy("","");
}
finally
{
}
Something like this? I think there is plenty of more simple ways in doing this.
string destination = "";
var fileInfo = new FileInfo(#"c:\temp\tips.txt");
var ext = fileInfo.Extension;
var filename = fileInfo.Name.Remove(fileInfo.Name.Length - 4);
File.Copy(fileInfo.FullName, destination + filename + " - Copy" + ext);
regarding Steve answer ("but if you really want to mimic the behaviour of Windows Explorer we should do:"), that I've found very useful, I have one comment:
The line:
if (file.EndsWith(" - Copy")) file = file.Remove(0, file.Length - 7);
Should be changed to:
if (file.EndsWith(" - Copy")) file = file.Remove(file.LastIndexOf(" - Copy"), file.Length - 7);
,since in case file ends with " - Copy" we loose the file name and remain with only the "Copy"(s).