-3

I have searched everywhere to find this answer but still can't find it.

I have a file in my Documents folder. I create and append a file with the same content in another folder. (Let's say Downloads). How do I give the new file the same name as the old file?

I just need help with naming the new file the same as the old. I already have it appending and sending to another folder. I'm using StreamReader to read the old file and StreamWriter to create the new file. I dont want to hard code a path to rename it, because there may be multiple files that I need to read.

3 Answers3

2

It's not clear exactly what you're asking for, but I'll take a stab at it.

If you're using something like the File.Copy() method, then you just have to use the full file path for both the source and destination. If you're passing a string value with the full path to the file, you can get just the file name using Path.GetFileName()

Here's an example based on my loose guesstimation of your question:

var filename = Path.GetFileName(sourcePath);
var newPath = $"{destinationFolderPath}\\{filename}";

File.Copy(sourcePath, newPath);

Additional Reading: https://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.110).aspx

https://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx

1

There is a static function Path.GetFilename, which returns a file name contained in a path passed as the argument:

var filename = Path.GetFilename(@"c:\file.txt"); // filename = "file.txt"

Path also contains other useful funtions, such as GetFilenameWithoutExtension.

Krzysztof Skowronek
  • 2,796
  • 1
  • 13
  • 29
1

Use Path.GetFileName i.e.

// The path you want to copy the filename of.
// C:/Users/<username>/Documents/<some file> in your case.
var srcPath = //...
// The directory you want to copy to.
// C:/Users/<username>/Downloads in your case.
var destDir = //...
// Different directory, same filename.
var destPath = Path.Combine(destDir, Path.GetFileName(srcPath));
Koby Duck
  • 1,118
  • 7
  • 15