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);
}
Related
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)));
}
}
I am trying to enumerate the zipped folders that are inside an unzipped folder using Directory.GetDirectories(folderPath).
The problem I have is that it does not seem to be finding the zipped folders, when I come to iterate over the string[], it is empty.
Is Directory.GetDirectories() the wrong way to go about this and if so what method serves this purpose?
Filepath example: C:\...\...\daily\daily\{series of zipped folder}
public void CheckZippedDailyFolder(string folderPath)
{
if(folderPath.IsNullOrEmpty())
throw new Exception("Folder path required");
foreach (var folder in Directory.GetDirectories(folderPath))
{
var unzippedFolder = Compression.Unzip(folder + ".zip", folderPath);
using (TextReader reader = File.OpenText(unzippedFolder + #"\" + new DirectoryInfo(folderPath).Name))
{
var csv = new CsvReader(reader);
var field = csv.GetField(0);
Console.WriteLine(field);
}
}
}
GetDirectories is the wrong thing to use. Explorer lies to you; zip files are actually files with an extension .zip, not real directories on the file system level.
Look at:
https://msdn.microsoft.com/en-us/library/system.io.compression.ziparchive.entries%28v=vs.110%29.aspx (ZipArchive.Entries) and/or
https://msdn.microsoft.com/en-us/library/system.io.compression.zipfile%28v=vs.110%29.aspx (ZipFile) to see how to deal with them.
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".
I have 800-1000 Uniquely named folders in one large folder.
Inside of each uniquely named folder is another folder called /images.
And inside of each image folder is a file named "Rock-Star-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"
I write a code that replaces all .png files (while keeping the original name) from a .png file which I supply.
The folder structure and filenames need to remain the same. Basically i am updating the old file with a new file, using the same (unique) name, 800-1000 times.
The code i have tried working properly but there is one mistake.There are plenty of images inside Image folder,But i need to update only "Rock-Star-Site-Design-{UNIQUEFOLDERNAME}-ca-logo.png"file every folder.
is there any way so i can get file.startwith("Rock-Star").So i can update particular file i want.
Here is my code:
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
foreach (var file in files)
{
if (!string.IsNullOrWhiteSpace(file))
{
File.Copy(Server.MapPath("ca-logo.jpg"), file,true);
}
}
}
catch (System.Exception excpt)
{
//MessageBox.Show(excpt.Message);
}
return files;
}
You can use this to get files based on a regular expression
Directory.GetFiles(sDir, "Rock-Star*.png");
Rock-Star*.png means files starting with Rock-Star, * means any character or sequence of characters, ending with .png
First get the file name from file full path using Path.GetFileName(). Then Use StartsWith(). When you add files to the list check if the file name starts with the name you want and then add to the list.
List<String> files = new List<String>();
foreach (string f in Directory.GetFiles(""))
{
//Get file name from full file path
string fileName = Path.GetFileName(f);
//Get only the files starts with Rock-Star
if (fileName.StartsWith("Rock-Star"))
{
files.Add(f);
}
}
EDIT
If you want to update the files with both upper and lower case lettes then you have to pass StringComparison.OrdinalIgnoreCase enumeration to your StartsWith() method
//Get only the files starts with Rock-Star or rock-start
if (fileName.StartsWith("Rock-Star",StringComparison.OrdinalIgnoreCase))
{
files.Add(f);
}
EDIT
To get files within all sub directories and replace, Pass SearchOption.AllDirectories to the GetFiles() method. Following code will search all the sub directories for files with .png extension
foreach (string f in Directory.GetFiles(sDir, "*.png", SearchOption.AllDirectories))
I am looking to create a program that finds all files of a certain type on my desktop and places them into specific folders, for example, I would have all files with .txt into the Text folder.
Any ideas what the best way would be to accomplish this? Thanks.
I have tried this:
string startPath = #"%userprofile%/Desktop";
string[] oDirectories = Directory.GetDirectories(startPath, "");
Console.WriteLine(oDirectories.Length.ToString());
foreach (string oCurrent in oDirectories)
Console.WriteLine(oCurrent);
Console.ReadLine();
It was not successful in finding all of the files.
A lot of these answers won't actually work, having tried them myself. Give this a go:
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);
}
It will move all .txt files on the desktop to the folder TextFiles.
First off; best practice would be to get the users Desktop folder with
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
Then you can find all the files with something like
string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);
Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.
Then you could copy or move the files by enumerating the above collection like
// For copying...
foreach (string s in files)
{
File.Copy(s, "C:\newFolder\newFilename.txt");
}
// ... Or for moving
foreach (string s in files)
{
File.Move(s, "C:\newFolder\newFilename.txt");
}
Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.
With that in mind you could also check out the DirectoryInfo and FileInfo classes.
These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily
Check out these for more info:
http://msdn.microsoft.com/en-us/library/system.io.directory.aspx
http://msdn.microsoft.com/en-us/library/ms143316.aspx
http://msdn.microsoft.com/en-us/library/system.io.file.aspx
You can try with Directory.GetFiles and fix your pattern
string[] files = Directory.GetFiles(#"c:\", "*.txt");
foreach (string file in files)
{
File.Copy(file, "....");
}
Or Move
foreach (string file in files)
{
File.Move(file, "....");
}
http://msdn.microsoft.com/en-us/library/wz42302f