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..
}
Related
I am working on an asp.net project using c# and I need to copy a file from an arbitrary location which is determined by the file upload dialog box.
I need to make an exact copy of the file in a folder that is located in the Solutions Explorer. Below is the code I am using.
string filename = txt_lesson_title.text;
string sourcepath = _Uploadedfile.PostedFile.FileName.ToString();
string targetPath = HttpContext.Current.Server.MapPath("/destFolder/");
File.Copy(sourcePath, targetPath + fileName);
The above code runs without reporting any errors but I cannot see the copied files in the destination folder. Any help will be deeply appreciated.
Thanks
You don't need to copy the file, you need to save a copy of it.
You can do this
if the file is coming to your controller, you controller should have arguments like HttpPostedFileBase or HttpPostedFileBase[] depending on if you are saving one or more
if you are saving one,
public ActionResult Step(FormCollection collection, HttpPostedFileBase file) {
//HttpPostedFileBase file; //this comes from you controller argument
var directory = "~/Uploads/";
//this if statement can be optional
if(!Directory.Exists(System.Web.HttpContext.Current.Server.MapPath(directory)))
{
Directory.CreateDirectory(System.Web.HttpContext.Current.Server.MapPath(directory));
var virtualPath = directory + "/" + <your file name here>;
var filePath = System.Web.HttpContext.Current.Server.MapPath(virtualPath);
//if the file exists already, delete and replace it with the new one
if (System.IO.File.Exists(filePath))
{
System.IO.File.Delete(filePath);
}
file.SaveAs(filePath);
}
else {
//do as above without the create directory
}
}
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");
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 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);
}
}
I have 4 directories that host different files in them.
I currently have a form that if a certain checkbox is checked, it is suppose to go to that directory, and find all the pdf's in that directory and add a prefix to them.
for example, say folder 1 has 5 pdf's in them. i want it to go through and add "some prefix" to the file name.
Before: Filename
After: Some Prefix Filename
Get all the files in the directory using Directory.GetFiles
For each file create a new file path using parent directory path, prefix string and file name
Use File.Move to rename the file.
It should be like:
var files = Directory.GetFiles(#"C:\yourFolder", "*.pdf");
string prefix = "SomePrefix";
foreach (var file in files)
{
string newFileName = Path.Combine(Path.GetDirectoryName(file), (prefix + Path.GetFileName(file)));
File.Move(file, newFileName);
}
string path = "Some Directory";
string prefix = "Some Prefix";
foreach (var file in Directory.GetFiles(path, "*.pdf"))
{
var newName = Path.Combine(Path.GetDirectoryName(file), prefix + Path.GetFileName(file));
File.Move(file, newName);
}