I have a folder that contains many png images in my resources of my WPF application. I would like to add this folder to appdata/roaming. Since there are many images that are sorted in folders, I would prefer to add the whole folder. Is there any way to do this?
By the way, the folder is in a directory called Resources and all the pngs are build as resources in Visual Studio.
Here is my code example for your question:
public void MyCopy()
{
//1.You can use the following code to get the path appdata/roaming, and suppose you want to copy the files to NewImageFolder
string strTarget = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).ToString() + "\\NewImageFolder\\";
if (!Directory.Exists(strTarget))
{
Directory.CreateDirectory(strTarget);
}
//2. Then you need to get the path of your the File to be copied
string strSource = AppDomain.CurrentDomain.BaseDirectory;
strSource = strSource.Substring(0, strSource.LastIndexOf("bin")) + "Resources\\Image";
//3.Copy the file
DirectoryInfo dir = new DirectoryInfo(strSource);
FileInfo[] files = dir.GetFiles();
string strFileName = null;
foreach (FileInfo file in files)
{
strFileName = strSource + "\\" + file.Name;
File.Copy(strFileName, System.IO.Path.Combine(strTarget, System.IO.Path.GetFileName(strFileName)));
}
}
Related
I have no problems when I want to create a new folder
I'm working with
Directory.CreateDirectory
Now I'm trying to get all image files from my desktop and I want to move all images to that folder which was created with Directory.CreateDirectory
I've testet file.MoveTo
from here
FileInfo file = new FileInfo(#"C:\Users\User\Desktop\test.txt");
to here
file.MoveTo(#"C:\Users\User\Desktop\folder\test.txt");
This works perfect.
Now I want to do that with all the image files from my dekstop
(Directory.CreateDirectory(#"C:\Users\User\Desktop\Images");)
How could I do that?
Example code of getting images with certain extentions from one root folder:
static void Main(string[] args)
{
// path to desktop
var desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//get file extentions by speciging the needed extentions
var images = GetFilesByExtensions(new DirectoryInfo(desktopPath) ,".png", ".jpg", ".gif");
// loop thrue the found images and it will copy it to a folder (make sure the folder exists otherwise filenot found exception)
foreach (var image in images)
{
// if you want to move it to another directory without creating a copy use:
image.MoveTo(desktopPath + "\\folder\\" + image.Name);
// if you want to move a copy of the image use this
File.Copy(desktopPath + "\\"+ image.Name, desktopPath + "\\folder\\" + image.Name, true);
}
}
public static IEnumerable<FileInfo> GetFilesByExtensions(DirectoryInfo dir, params string[] extensions)
{
if (extensions == null)
throw new ArgumentNullException("extensions");
var files = dir.EnumerateFiles();
return files.Where(f => extensions.Contains(f.Extension));
}
Please try this:
You can filter files in a specific directory and then looop through search results to move each file, you might be able to modify search pattern to match on a number of different image file formats
var files = Directory.GetFiles("PathToDirectory", "*.jpg");
foreach (var fileFound in files)
{
//Move your files one by one here
FileInfo file = new FileInfo(fileFound);
file.MoveTo(#"C:\Users\User\Desktop\folder\" + file.Name);
}
I want to copy and paste sub-folders of source folder ABC To destination folder. But it is not working. Here is my C# code, it work's fine but it copies the whole folder instead of only the sub-folders.
// string fileName = "test.txt";
string sourcePath = "D:\\Shraddha\\Demo_Web_App\\Source";
string targetPath = "D:\\Shraddha\\Demo_Web_App\\Destination";
// Use Path class to manipulate file and directory paths.
string sourceFile = System.IO.Path.Combine(sourcePath);
string destFile = System.IO.Path.Combine(targetPath);
// 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
{
Console.WriteLine("Source path does not exist!");
}
// Keep console window open in debug mode.
Console.WriteLine("Press any key to exit.");
Console.ReadKey();
Alright, here we go:
This doesn't really makes sense. If targetPath exists, create targetPath folder?
if (System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
You probably meant:
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
}
What you need to do first is, getting all directories to begin with:
var allDirectories = Directory.GetDirectories(targetPath, "*", SearchOption.AllDirectories);
then you can loop through allDirectories with foreach, find all files in each folder and copy the contents.
The following line cannot work like provided:
destFile = System.IO.Path.Combine(targetPath);
File.Copy expects a path to a file where you want to copy the content from "s", but you are providing only the destination folder. You have to include a filename in the Path.Combine method.
If you parse the path strings with the Path.GetFileName method for example, you can pass the result (only the filename without full source path) as an additional argument to Path.Combine to generate a valid destination path.
Additionally, like uteist already said, you have to get all subdirectories first, because in your code example, you're only copying the files, directly placed under your root source folder.
To keep the Directory structure
foreach (var dir in System.IO.Directory.GetDirectories(sourcePath))
{
var dirInfo = new System.IO.DirectoryInfo(dir);
System.IO.Directory.CreateDirectory(System.IO.Path.Combine(targetPath, dirInfo.Name));
foreach (var file in System.IO.Directory.GetFiles(dir))
{
var fileInfo = new System.IO.FileInfo(file);
fileInfo.CopyTo(System.IO.Path.Combine(targetPath, dirInfo.Name, fileInfo.Name));
}
};
I have a number of kml file I am generating in a directory.
I am wondering if there is a way to group them all into a kmz file programmatically in C#. With a name and description displayed in google earth.
Thanks and best regards,
private static void combineAllKMLFilesULHR(String dirPath)
{
string kmzPath = "outputULHR.kmz";
string appPath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
string rootKml = appPath + #"\" + dirPath + #"\doc.kml";
Console.WriteLine(appPath + #"\"+ dirPath);
String[] filepaths = Directory.GetFiles(appPath + #"\" + dirPath);
using (ZipArchive archive = ZipFile.Open(kmzPath, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile( rootKml, "doc.kml");
foreach (String file in filepaths)
{
Console.WriteLine(file);
if(!file.Equals(rootKml))
archive.CreateEntryFromFile( file, Path.GetFileName(file) );
}
}
}
Being a KMZ file a zip archive, you can use the ZipArchive class to generate it.
string kmzPath = "output.kmz";
string rootKml = "doc.kml";
string referencedKml = "someother.kml";
using (ZipArchive archive = ZipFile.Open(kmzPath, ZipArchiveMode.Create))
{
archive.CreateEntryFromFile(rootKml, "doc.kml");
archive.CreateEntryFromFile(referencedKml, "someother.kml");
}
just remember to name the default kml as doc.kml, from the documentation:
Put the default KML file (doc.kml, or whatever name you want to give
it) at the top level within this folder. Include only one .kml file.
(When Google Earth opens a KMZ file, it scans the file, looking for
the first .kml file in this list. It ignores all subsequent .kml
files, if any, in the archive. If the archive contains multiple .kml
files, you cannot be sure which one will be found first, so you need
to include only one.)
guys. I've got a problem I can't solve:
I have a 2 folders I choose with folderBrowserDialog and tons of files in source directory I need to move to the target directory. But, I have only to move files with a specific extension like .txt or any other extension I can get from textbox.
So how can I do it?
First get all the files with specified extension using Directory.GetFiles() and then iterate through each files in the list and move them to target directory.
//Assume user types .txt into textbox
string fileExtension = "*" + textbox1.Text;
string[] txtFiles = Directory.GetFiles("Source Path", fileExtension);
foreach (var item in txtFiles)
{
File.Move(item, Path.Combine("Destination Directory", Path.GetFileName(item)));
}
Try this:
For copying files...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
for moving files
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Example for Moving files to Directory:
string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);
foreach (var file in d.GetFiles("*.txt"))
{
Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}
will Move all the files from Desktop to Directory "TextFiles".
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));
}
}