How to get file from the root folder? - c#

I had One folder. That folder contains so many sub folders. That each sub folders has so many folders and folder MNC. that MNC folder contains so many files and also .txt files. How to get that .txt files when I give the path of that main root folder. i.e For Example, I have a root folder name A. A folder contains so many sub folders. That each sub folders have so many folders and folder MNC and MNC folder had so many files and also .txt files. If I give the path of folder A then It should give the .txt files as output. I tried some types. But I can't get the correct output. Please help me for this. Thanks in advance.

You can get all txt files by executing:
//Gets all *.txt files
string rootDir = #"C:\\Dokumentai\\Files\\A";
var txtFiles = Directory.GetFiles(rootDir, "*.txt", SearchOption.AllDirectories);
Console.WriteLine("txtFiles count:" + txtFiles.Count());
//Filter only txt files from "root\[any folder]\MNC\*.txt",
//the pattern can be improoved, becouse it takes all TXT files from from MNC folder including it subfolders...
string patternt = rootDir+#"\\(.*)\\MNC\\(.*).txt";
//From each file before compare raplacing "\\" to "\"
var txtFilesOnlyFromMncFolders = txtFiles.Where(filePath => Regex.IsMatch( filePath.Replace(#"\\", #"\"), patternt, RegexOptions.IgnoreCase)).ToList();
Console.WriteLine("txtFiles count:" + txtFilesOnlyFromMncFolders.Count());
// Printing founded files for debug purpose
foreach (var file in txtFilesOnlyFromMncFolders)
{
Console.WriteLine(file);
}
Then you can get content of file by
foreach(file in txtFiles)
{
//Check if file exists
if (File.Exists(file))
{
//Do something with file content
string fileContent = File.ReadAllText(file);
}
}

Related

How do I add a resource folder to app data?

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)));
}
}

c# - How to assign resources folder to a string

I'm currently using this,
string finename = "text.txt"; //setting file name
//setting locations
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string filepath = #"C:\User\Users\Documents\Files\Apple"; // <--- need to use Resources folder in the project folder here
//filename and location combining to be copied
string source = Path.Combine(filepath,filename);
string destination = Path.Combine(path,filename);
if (something=1)
{
File.Copy(source,destination, true); //copying
}
I've added all the files to the Resources now i need to refer to Resources folder instead of "filepath" here,
is there any way to assign the resources folder (& its contents) to a string so i can simply change the location? then i can use this code on other PC's also.
Edit -
Imagine i have orange,mango and apple folder inside the resource folder, and each of these 3 folders contain a text file with the name "text.txt".
And i need to copy one of these text files from each & every fruit folder on request & paste it on desktop.
Now i need to store the location of "Resources\apple" , "Resources\orange" & "Resources\mango" on 3 different strings so i can simply call them in the "string source = Path.Combine(filepath,filename)" part instead of older "filepath" to copy those text files from any of the fruit folder inside resources folder to the desktop.
thanks.
Get src or root folder path.
Combine root folder path with your resource folder path.
Combine result(root\resources) with your file name
Here you go, you will get exact path of file and now you can copy it to the destination.
Here is the implementation: This code is running on my machine.
/// <summary>
/// Here you just need to send fruit name
/// </summary>
/// <param name="fruitName">Name of fruit</param>
public void CopyFile(string fruitName)
{
string filename = "text.txt"; //setting file name
string resouceFolderName = Path.Combine("Resources", fruitName);
//Destination Path
string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
//CurrentDirectory return src\\Bin\\Debug so extracting src root folder path
string parentFolderPath = Directory.GetParent(Directory.GetParent(Environment.CurrentDirectory).FullName).FullName;
//combining parent folder path with resource folder name
string folderPath = Path.Combine(parentFolderPath, resouceFolderName); // <--- need to use Resources folder in the project folder here
//Checking if exist or not
if (!Directory.Exists(folderPath) || !Directory.Exists(path))
{
Console.WriteLine("Error");
return;
}
//filename and location combining to be copied
string source = Path.Combine(folderPath, filename);
string destination = Path.Combine(path, filename);
if (true)
{
File.Copy(source, destination, true); //copying
}
}
Note: Here I used test.txt and Resources string as a constant considering they won't change
Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
What you are doing here is retrieving the path to your desktop and copying your .txt file from your filepath to there.
You are not copying the file onto your project "Resources" folder.
In case your file is there as #Prasad telkikar said, with the following code you would have the path to your's "Resource" folder and be able to access all the content inside it.
string path = Path.Combine(Environment.CurrentDirectory, "Resources");

How to move subfolder with files to another directory in asp.net C#

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));
}
};

How to rename files in unknown directory using c#

I want to rename a file with particular extension present inside a folder. For example C:\Users\Username\Desktop\Convert is the file location I'm in. There be another folder for example "C:\Users\Username\Desktop\Convert\Unknown folder". I wont be knowing the name of this unknown folder. There will be a .txt file inside that unknown folder. So how will I access the unknown folder and change the extension of the .txt file to .jpg ?
This is what i have tried and its not working :
string ourPath = #"C:\Users\username\Desktop\Convert\123.txt";
string newPath = Path.ChangeExtension(ourPath, "jpg");
File.Move(ourPath, newPath);
}
Get all the files in descendant folders using SearchOption.AllDirectories then find your file and do whatever you want:
var files = Diretory.GetFiles(
#"C:\Users\Username\Desktop\Convert",
"*.txt",
SearchOption.AllDirectories);
var filePath = files.FirstOrDefault(f => Path.GetFileName(f) == "123.txt");
if(filePath != null)
{
// manipulate the file ext. etc..
}

Visual C#: Move multiple files with the same extensions into another directory

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".

Categories