Command to copy a file to another directory? - c#

I do this code to copy a file to another destination, but i need the his name ( to the copied file) with the date and hour of my PC ... what's wrong ??
string fileToCopy = "d:\\pst\\2015.pst";
string destinationDirectory ="C:\\Users\\pierr_000\\Desktop\\New folder (3)\\ba-{0:MM-DD_hh-mm}.pst";
File.Copy(fileToCopy, destinationDirectory + Path.GetFileName(fileToCopy));

It's not working because destinationDirectory is referring to a file. Use Path.GetDirectoryName to retrieve the actual directory and Path.Combine to combine paths.
File.Copy(fileToCopy, Path.Combine(Path.GetDirectoryName(String.Format(destinationDirectory, DateTime.Now)), Path.GetFileName(fileToCopy)));

There are a number of issues with your code.
Your format string is incorrect. The day of month is represented by dd not DD.
You aren't using your format string in any meaningful way.
You are concatenating strings rather that using System.IO.Path to construct paths.
It looks like you're trying to do the following:
string fileToCopy = #"d:\pst\2015.pst";
string destinationDirectoryTemplate =
#"C:\Users\pierr_000\Desktop\New folder (3)\ba-{0:MM-dd_hh-mm}";
var dirPath = string.Format(destinationDirectoryTemplate, DateTime.UtcNow);
var di = new DirectoryInfo(dirPath);
if(!di.Exists)
{
di.Create();
}
var fileName = Path.GetFileName(fileToCopy);
var targetFilePath = Path.Combine(dirPath, fileName);
File.Copy(fileToCopy, targetFilePath);

Related

Need to remove duplicate text from file names dynamically

Due to a bug in their exporter, a client has a list of files where the file name is being duplicated.
For example:
ThisIs-MyFile-1ThisIs-MyFile-1.jpg
ThisIs-MyFile-2ThisIs-MyFile-2.jpg
While fixing the exporter is obviously the best solution, in the meantime, it would be great to be able to correct the files that they've already exported. I would like to iterate over these files and find the duplicate text in each string and remove it.
How might this be implemented?
Thanks.
Edit:
To be clear, the file names do not share the pattern above in that it isn't just a matter of the number changing. Those are simply placeholders for repeated names.
It could just as easily be:
heyHowAreYou-1heyHowAreYou-1.png
ImOkThanksImOkThanks.pdf
If you know that the filename is always duplicated, you can do something like this:
Grab the filename and the extension of the file you want to "fix"
Remove half of the filename (the duplicated part)
Rename the file using the fixed name
So you should end up with something like this
string originalFile = "ThisIs-MyFile-1ThisIs-MyFile-1.jpg";
string fileName = Path.GetFileNameWithoutExtension(originalFile);
string extension = Path.GetExtension(originalFile);
fileName = fileName.Substring(0, fileName.Length / 2);
File.Move(originalFile, $"{fileName}{extension}");
Of course you should find a way to iterate in a folder instead of manually specify the file names, but that is up to you
Here you go
var dir = new DirectoryInfo(folderpath);
var files = dir.GetFiles();
foreach (FileInfo f in files)
{
var oldname = Path.GetFileNameWithoutExtension(f.Name);
var newname = oldname.Substring(0, oldname.Length / 2);
File.Move(f.FullName, f.FullName.Replace(oldname, newname));
}
As commented take the half of the string.
Try this:
fileName = fileName.Substring(0, fileName.Length / 2);
I assume fileName is the name of the file without file extension
Try:
var file = "ThisIs-MyFile-1ThisIs-MyFile-1.jpg";
// Split to remove file extension.
var splits = file.Split(new[] { '.' });
// Take half the file name.
var fileName = splits[0].Substring(0, splits[0].Length/2);
// Add the extension back.
var newFile = $"{fileName}.{splits[1]}";
You could use the FileInfo.Extension property to remove the extension, then substring half the string and concatenate with the extension:
var fileInfo = new FileInfo(filePath);
var nameWithoutExtension = fileInfo.Name.Replace(fileInfo.Extension, string.Empty);
var newName = $"{nameWithoutExtension.Substring(0, nameWithoutExtension.Length / 2)}{fileInfo.Extension}";

Find file with Name and Extension

I want to find a file that has .pdf extension and I want to find with name too. For example I have filename = "Work.pdf". I want to write a method that
could find with name. Is there any builtin method for this?
string fileName = "Work.pdf"
string[] files = System.IO.Directory.GetFiles("C:\Files", "*.pdf");
// string myWorkPdfFile = files.Where() //search the files with fileName
You can try to pass fileName value be second parameter.
string fileName = "Work.pdf";
string[] files = System.IO.Directory.GetFiles(#"C:\Files", fileName);

How to create a folder out of the first few letters of a filename?

So I checked out the basic things but I'd like to do the following:
I have 5 files let's say: X1_word_date.pdf, XX1_word_date.pdf, etc...
I'd like to create a folder structure like: C:\PATH\X1, C:\PATH\XX1, etc...
So how do I take the first letters before the '_' in the file names and put it into a string?
My idea is that I use the Directory.CreateDirectory and than combine the main path and the strings so I get the folders.
How do I do that? Help appreciated.
string fileName = "X1_word_date.pdf";
string[] tokens = fileName.Split('_');
string myPath = "C:\\PATH\\";
Directory.CreateDirectory( myPath + tokens[0]);
Something like this should work. Using Split() will also allow for numbers greater than 9 to be dealt with
Supposed that your files is a List<string> which contains the file name (X2_word_date.pdf,...)
files.ForEach(f => {
var pathName= f.Split('_').FirstOrDefault();
if(!string.IsNullOrEmpty(pathName))
{
var directoryInfo = DirectoryInfo(Path.Combine(#"C:\PATH", pathName));
if(!directoryInfo.Exists)
directoryInfo.Create();
//Then move this current file to the directory created, by FileInfo and Move method
}
})
With simple string methods like Split and the System.IO.Path class:
var filesAndFolders = files
.Select(fn => new
{
File = fn,
Dir = Path.Combine(#"C:\PATH", Path.GetFileNameWithoutExtension(fn).Split('_')[0].Trim())
});
If you want to create that folder and add the file:
foreach (var x in filesAndFolders)
{
Directory.CreateDirectory(x.Dir); // will only create it if it doesn't exist yet
string newFileName = Path.Combine(x.Dir, x.File);
// we don't know the old path of the file so i can't show how to move
}
Or using regex
string mainPath = #"C:\PATH";
string[] filenames = new string[] { "X1_word_date.pdf", "X2_word_date.pdf" };
foreach (string filename in filenames)
{
Match foldernameMatch = Regex.Match(filename, "^[^_]+");
if (foldernameMatch.Success)
Directory.CreateDirectory(Path.Combine(mainPath, foldernameMatch.Value));
}
Using the bigger picture starting with only your Source and Destination directory.
We can list all files we need to move with Directory.GetFiles.
In this list We first isolate the filename with GetFileName.
Using simple String.Split you have the new directory name.
Directory.CreateDirectory will create directories unless they already exist.
To move the file we need its destination path, a combinaison of the Destination directory path and the fileName.
string sourceDirectory = #"";
string destDirectory = #"";
string[] filesToMove = Directory.GetFiles(sourceDirectory);
foreach (var filePath in filesToMove) {
var fileName = Path.GetFileName(filePath);
var dirPath = Path.Combine(destDirectory, fileName.Split('_')[0]);
var fileNewPath= Path.Combine(dirPath,fileName);
Directory.CreateDirectory(dirPath);// If it exist it does nothing.
File.Move(filePath, fileNewPath);
}

How to enter a folder without knowing its name?

I need to read a text file that I know its full path, except one folder's name. I' d use
string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName);
but first, I need to find out unknownFolderName to reach the file' s full path. There is exactly one folder under path, all I need to do is entering under this folder, without knowing its name. How can I achieve this in simplest way?
You could try using Directory.GetDirectories(). If you're guaranteed to only have one folder underneath that folder, then you should be able to do it VIA:
string unknownPath = Directory.GetDirectories(path)[0];
//Now instead of this: [ string readText = File.ReadAllText(path + "\\" + unknownFolderName + "\\" + itemName) ], do this:
string readText = File.ReadAllText(unknownPath + "\\" + itemName);
That should do it. Let me know if it works out for you!
You could use Directory.GetDirectories static method (documentation) which returns the array of strings - full paths to the direcotries in the path you passed to the method. So try something like this (if you are sure that there is at least one directory and you want to use the first one):
string readText = File.ReadAllText(Directory.GetDirectories(path)[0] + "\\" + itemName);
In case you have more than one folder, and you don't know which one is:
Take a look at the following example. You're looking for Windows in the following path: C:\_____\System32\notepad.exe
string path = #"C:\";
var itemName = #"System32\notepad.exe";
var directories = Directory.GetDirectories(path);
foreach (var dir in directories) {
string fullPath = Path.Combine(dir, itemName);
//If you found the correct directory!
if (File.Exists(fullPath)) {
Console.WriteLine(fullPath);
}
}
Use this to get the folder names under your directory:
http://www.developerfusion.com/code/4359/listing-files-folders-in-a-directory/

Get folder name from full file path

How do I get the folder name from the full path of the application?
This is the file path below,
c:\projects\root\wsdlproj\devlop\beta2\text
Here "text" is the folder name.
How can I get that folder name from this path?
See DirectoryInfo.Name:
string dirName = new DirectoryInfo(#"c:\projects\roott\wsdlproj\devlop\beta2\text").Name;
I think you want to get parent folder name from file path. It is easy to get.
One way is to create a FileInfo type object and use its Directory property.
Example:
FileInfo fInfo = new FileInfo("c:\projects\roott\wsdlproj\devlop\beta2\text\abc.txt");
String dirName = fInfo.Directory.Name;
Try this
var myFolderName = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
var result = Path.GetFileName(myFolderName);
You could use this:
string path = #"c:\projects\roott\wsdlproj\devlop\beta2\text";
string lastDirectory = path.Split(new char[] { System.IO.Path.DirectorySeparatorChar }, StringSplitOptions.RemoveEmptyEntries).Last();
Simply use Path.GetFileName
Here - Extract folder name from the full path of a folder:
string folderName = Path.GetFileName(#"c:\projects\root\wsdlproj\devlop\beta2\text");//Return "text"
Here is some extra - Extract folder name from the full path of a file:
string folderName = Path.GetFileName(Path.GetDirectoryName(#"c:\projects\root\wsdlproj\devlop\beta2\text\GTA.exe"));//Return "text"
I figured there's no way except going into the file system to find out if text.txt is a directory or just a file. If you wanted something simple, maybe you can just use:
s.Substring(s.LastIndexOf(#"\"));
In this case the file which you want to get is stored in the strpath variable:
string strPath = Server.MapPath(Request.ApplicationPath) + "/contents/member/" + strFileName;
Here is an alternative method that worked for me without having to create a DirectoryInfo object. The key point is that GetFileName() works when there is no trailing slash in the path.
var name = Path.GetFileName(path.TrimEnd(Path.DirectorySeparatorChar));
Example:
var list = Directory.EnumerateDirectories(path, "*")
.Select(p => new
{
id = "id_" + p.GetHashCode().ToString("x"),
text = Path.GetFileName(p.TrimEnd(Path.DirectorySeparatorChar)),
icon = "fa fa-folder",
children = true
})
.Distinct()
.OrderBy(p => p.text);
This can also be done like so;
var directoryName = System.IO.Path.GetFileName(#"c:\projects\roott\wsdlproj\devlop\beta2\text");
Based on previous answers (but fixed)
using static System.IO.Path;
var dir = GetFileName(path?.TrimEnd(DirectorySeparatorChar, AltDirectorySeparatorChar));
Explanation of GetFileName from .NET source:
Returns the name and extension parts of the given path. The resulting
string contains the characters of path that follow the last
backslash ("\"), slash ("/"), or colon (":") character in
path. The resulting string is the entire path if path
contains no backslash after removing trailing slashes, slash, or colon characters. The resulting
string is null if path is null.

Categories

Resources