how do i allow this code to retrieve the files from a directory? For example, my directory name is "Folder Name":
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { FileName = filePath });
return files;
}
EDIT:
I've tried this, and it still isn't working:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames())
files.Add(new FileItem { "FlashCardApp\\" + FileName = filePath });
return files;
}
I've finally found the answer to my own question.
This is how it is suppose to be:
private ObservableCollection<FileItem> LoadFiles()
{
ObservableCollection<FileItem> files = new ObservableCollection<FileItem>();
foreach (string filePath in this.Store.GetFileNames("FlashCardApp\\"))
files.Add(new FileItem { FileName = filePath });
return files;
}
By having \ after the folder name, "FlashCardApp\\", it will retrieve the files from the directory.
DirectoryInfo di = new DirectoryInfo("c:/Folder Name");
FileInfo[] rgFiles = di.GetFiles("*.*");
foreach(FileInfo fi in rgFiles)
{
//Do something
fi.Name
}
To retrieve file names, you can use System.IO:
string[] filePaths = Directory.GetFiles(path, "*.txt")
The Directory class is in System.IO.
I doubth that your folder name is correct. I'll recommend you use storeFile.GetDirectoryNames("*") to see what the correct paths for the directory is.
Microsoft wrote a great example I think you should try and take a look at, since there's nothing obvious wrong with your code.
Related
I want to copy some of the content of a folder (recursively). only files that contain a specific pattern.
Here there's a method that copies the entire content. no matter what files inside.
https://stackoverflow.com/a/3822913/7028967
Do you have any ideas on how can I copy a specific file inside some subfolder with a given pattern?
for example:
-- rootFolder
---- filename.txt
CopyContent(src, dest, *.txt)
Below sample code to copy all the files from the source directory to destination folder in exact same folder structure :
public static void Copy()
{
string sourceDir = #"C:\test\source\";
string destination = #"C:\test\destination\";
string[] textFiles = Directory.GetFiles(sourceDir, "*.txt", SearchOption.AllDirectories);
foreach (string textFile in textFiles)
{
string fileName = textFile.Substring(sourceDir.Length);
string directoryPath = Path.Combine(destination, Path.GetDirectoryName(fileName));
if (!Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);
File.Copy(textFile, Path.Combine(directoryPath, Path.GetFileName(textFile)), true);
}
}
Updated:
I used this solution. and it works for me!
private static void CopyContentFolder(string sourcePath, string targetPath, bool isFileOverridable, string pattern = "*.*")
{
string[] sourceFiles = Directory.GetFiles(sourcePath, pattern, SearchOption.AllDirectories);
foreach (string sourceFilePath in sourceFiles)
{
string destinationFilePath = string.Empty;
destinationFilePath = sourceFilePath.Replace(sourcePath, targetPath);
EvaluatePath(destinationFilePath);
File.Copy(sourceFilePath, destinationFilePath, isFileOverridable);
}
}
private static void EvaluatePath(string path)
{
try
{
string folder = Path.GetDirectoryName(path);
if (!Directory.Exists(folder))
{
DirectoryInfo di = Directory.CreateDirectory(folder);
}
}
catch (IOException ioex)
{
Console.WriteLine(ioex.Message);
}
}
I need some help.
I just have this code right now. This code is working, but it's not enough.
My code;
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
foreach (FileInfo currentFile in infoFile)
{
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName))
{
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
foreach (ZipEntry currentZip in zipFile)
{ currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently); }
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
I want to extract all zip files to Application.StartupPath folder from _ZipFiles folder with all subdirectories.
Here is one example;
I have one zip folder. Name: _ZipFolder
Before the unzip process;
Application.StartupPath\_ZipFiles\startProgram.zip
Application.StartupPath\_ZipFiles\updateProgram.zip
Application.StartupPath\_ZipFiles\Pack\testDownload.zip
Application.StartupPath\_ZipFiles\Pack\Version\repo2.zip
Application.StartupPath\_ZipFiles\Pack\Version\newClass.zip
Application.StartupPath\_ZipFiles\Ack\Library\argSetup.zip
Application.StartupPath\_ZipFiles\Ack\learnMachine.zip
Application.StartupPath\_ZipFiles\Code\zipVersion4.zip
After the unzip process (I exactly want to this extract);
Application.StartupPath\startProgram.exe
Application.StartupPath\updateProgram.exe
Application.StartupPath\Pack\testDownload.exe
Application.StartupPath\Pack\Version\repo2.cs
Application.StartupPath\Pack\Version\newClass.cs
Application.StartupPath\Ack\Library\argSetup.exe
Application.StartupPath\Ack\learnMachine.pdf
Application.StartupPath\Code\zipVersion4.exe
All files needs move to Application.StartupPath from _ZipFiles folder with subdirectories.
How to make this? Please help me.
I hope you understand what I want. I'm sorry for my bad English.
Remove the zip folder name from the current file directory name when extracting
Based on current example where you have _ZipFiles folder
DirectoryInfo dirFile = new DirectoryInfo(currentDir);
FileInfo[] infoFile = dirFile.GetFiles("*.zip", SearchOption.AllDirectories);
var zipFolderName = #"\_ZipFiles";
foreach (FileInfo currentFile in infoFile) {
using (ZipFile zipFile = ZipFile.Read(currentFile.FullName)) {
zipFile.ExtractProgress += new EventHandler<ExtractProgressEventArgs>(unZipFiles_ExtractProgressChanged);
var destination = currentFile.DirectoryName.Replace(zipFolderName, "");
foreach (ZipEntry currentZip in zipFile) {
currentZip.Extract(destination, ExtractExistingFileAction.OverwriteSilently);
}
}
currentCount = increaseCount + 1; increaseCount = currentCount;
if (downloadType == 1) { bar2SetProgress((ulong)currentCount, (ulong)totalCount); }
lblFileName.Text = currentFile.Name;
}
If I understood you correctly, you want to extract all files to Application.StartupPath directory instead in subfolders.
Try to change:
currentZip.Extract(currentFile.DirectoryName, ExtractExistingFileAction.OverwriteSilently);
to
currentZip.Extract(Application.StartupPath, ExtractExistingFileAction.OverwriteSilently);
If Application.StartupPath isn't suitable, then maybe use AppDomain.CurrentDomain.BaseDirectory
Good day.
I have to copy all the files in folders (including sub folders) to other shared drive location for backup the data. The challenge, which I am facing is folder path with wildcard characters.
For example,
The folder structure is like below
D:/Folder1/Folder11/Folder111
D:/Folder2/Folder222/Folder222222
D:/Folder3/Folder333333/Folder3333333
I am looking for the input format should be "D:/Folder?/Folder*/Folder*". So that it has to loop according to the wildcard character patterns.
Can you please help me.
Regards,
Chandra
You can achive this with a simple RegularExpression. I've created an example which does the job for you.
The RegEx string is quite easy: [A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}
----- -------- -------- --------
Drive 1x digit 2x digit 3x digit
See the sample at regexr.
EDIT:
//using System.IO;
public void CopyMatching(string drive)
{
try
{
var backuplocation = ""; //the path where you wanna copy your files to
var regex = new Regex(#"[A-Z]:\\Folder[0-9]{1}\\Folder[0-9]{2}\\Folder[0-9]{3}");
var directories = new List<string>();
foreach (var directory in Directory.EnumerateDirectories(drive))
{
if (regex.IsMatch(directory))
{
directories.Add(directory);
}
}
foreach (var directory in directories)
{
DirectoryCopy(directory, backuplocation, true);
}
}
catch (Exception)
{
throw;
}
}
And DirectoryCopy:
public void DirectoryCopy(string sourceDirName, string destDirName, bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
IEnumerable<string> getMatchingSubDir(string dirPath, string pattern)
{
List<string> matchingFolders = new List<string>();
DirectoryInfo myDir = new DirectoryInfo(dirPath);
foreach (var subDir in myDir.GetDirectories(pattern))
{
matchingFolders.AddRange(getMatchingSubDir(subDir.FullName, pattern));
}
return matchingFolders;
}
Then this call will return you a list of all folders matching your pattern:
getMatchingSubDir("D:\\", "Folder*");
I found a small snippet for doing a recursive file copy in C#, but am somewhat stumped. I basically need to copy a directory structure to another location, along the lines of this...
Source: C:\data\servers\mc
Target: E:\mc
The code for my copy function as of right now is...
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(baseDir, "*", SearchOption.AllDirectories))
{
Directory.CreateDirectory(dirPath.Replace(baseDir, targetDir));
}
// Copy each file into it’s new directory.
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
Console.WriteLine(#"Copying {0}\{1}", targetDir, Path.GetFileName(file));
if (!CopyFile(file, Path.Combine(targetDir, Path.GetFileName(file)), false))
{
int err = Marshal.GetLastWin32Error();
Console.WriteLine("[ERROR] CopyFile Failed on {0} with code {1}", file, err);
}
}
The issue is that in the second scope, I either:
use Path.GetFileName(file) to get the actual file name without the path but I lose the directory "mc" directory structure or
use "file" without Path.Combine.
Either way I have to do some nasty string work. Is there a good way to do this in C# (my lack of knowledge with the .NET API leads me to over complicating things)
MSDN has a complete sample: How to: copy directories
using System;
using System.IO;
class DirectoryCopyExample
{
static void Main()
{
// Copy from the current directory, include subdirectories.
DirectoryCopy(".", #".\temp", true);
}
private static void DirectoryCopy(string sourceDirName, string destDirName,
bool copySubDirs)
{
// Get the subdirectories for the specified directory.
DirectoryInfo dir = new DirectoryInfo(sourceDirName);
if (!dir.Exists)
{
throw new DirectoryNotFoundException(
"Source directory does not exist or could not be found: "
+ sourceDirName);
}
DirectoryInfo[] dirs = dir.GetDirectories();
// If the destination directory doesn't exist, create it.
if (!Directory.Exists(destDirName))
{
Directory.CreateDirectory(destDirName);
}
// Get the files in the directory and copy them to the new location.
FileInfo[] files = dir.GetFiles();
foreach (FileInfo file in files)
{
string temppath = Path.Combine(destDirName, file.Name);
file.CopyTo(temppath, false);
}
// If copying subdirectories, copy them and their contents to new location.
if (copySubDirs)
{
foreach (DirectoryInfo subdir in dirs)
{
string temppath = Path.Combine(destDirName, subdir.Name);
DirectoryCopy(subdir.FullName, temppath, copySubDirs);
}
}
}
}
A non-recursive replacement for this answer would be:
private static void DirectoryCopy(string sourceBasePath, string destinationBasePath, bool recursive = true)
{
if (!Directory.Exists(sourceBasePath))
throw new DirectoryNotFoundException($"Directory '{sourceBasePath}' not found");
var directoriesToProcess = new Queue<(string sourcePath, string destinationPath)>();
directoriesToProcess.Enqueue((sourcePath: sourceBasePath, destinationPath: destinationBasePath));
while (directoriesToProcess.Any())
{
(string sourcePath, string destinationPath) = directoriesToProcess.Dequeue();
if (!Directory.Exists(destinationPath))
Directory.CreateDirectory(destinationPath);
var sourceDirectoryInfo = new DirectoryInfo(sourcePath);
foreach (FileInfo sourceFileInfo in sourceDirectoryInfo.EnumerateFiles())
sourceFileInfo.CopyTo(Path.Combine(destinationPath, sourceFileInfo.Name), true);
if (!recursive)
continue;
foreach (DirectoryInfo sourceSubDirectoryInfo in sourceDirectoryInfo.EnumerateDirectories())
directoriesToProcess.Enqueue((
sourcePath: sourceSubDirectoryInfo.FullName,
destinationPath: Path.Combine(destinationPath, sourceSubDirectoryInfo.Name)));
}
}
instead of
foreach (string file in Directory.GetFiles(baseDir, "*.*", SearchOption.AllDirectories))
{
do something like this
foreach (FileInfo fi in source.GetFiles())
{
fi.CopyTo(Path.Combine(target.ToString(), fi.Name), true);
}
How to copy all *.bak files from Directory A to Directory B?
This should do what you need:
string dirA = #"C:\";
string dirB = #"D:\";
string[] files = System.IO.Directory.GetFiles(dirA);
foreach (string s in files) {
if (System.IO.Path.GetExtension(s).equals("bak")) {
System.IO.File.Copy(s, System.IO.Path.Combine(targetPath, fileName), true);
}
}
I'm not going to give you the full solution, but check out Directory.GetFiles (which takes a search pattern) and File.Copy.
Those two methods are everything you need.
There's two ways, the pure C# way:
var items = System.IO.Directory.GetFiles("Directory A", "*.bak", System.IO.SearchOption.TopDirectoryOnly);
foreach(String filePath in items)
{
var newFile = System.IO.Path.Combine("Directory B", System.IO.Path.GetFileName(filePath));
System.IO.File.Copy(filePath, newFile);
}
The robocopy way:
var psi = new System.Diagnostics.ProcessStartInfo();
psi.FileName = #"C:\windows\system32\robocopy.exe";
psi.Arguments = "Directory A Directory B *.bak";
System.Diagnostics.Process.Start(psi);
use this link http://www.codeproject.com/KB/cs/Execute_Command_in_CSharp.aspx
to execute
xcopy /y /f PathOfA\*.bak PathOfB\
My improvement on above suggestions:
public static void CopyFilesWithExtension(string src, string dst, string extension)
{
string[] files = System.IO.Directory.GetFiles(src);
foreach (string s in files)
{
if (System.IO.Path.GetExtension(s).Equals(extension))
{
var filename = System.IO.Path.GetFileName(s);
System.IO.File.Copy(s, System.IO.Path.Combine(dst, filename));
}
}
}
Usage:
Utils.CopyFilesWithExtension(#"C:\src_folder",#"C:\dst_folder",".csv");