Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add file extension to extension-less file

Tags:

c#

I'm trying to add an extension to a file that is selected in an OpenFileDialog in my C# app. I'm having difficulty with files that don't already have an extension.

While I haven't tested the following method on files with an extension, I know that it doesn't work for files without an extension (which is really what I want to work with here).

string tPath = videoPath + videoName;
string tPath2 = Path.ChangeExtension(tPath, ".yuv");

tPath2 will reflect to header change, but it seems not to affect the file itself, only the string returned by the ChangeExtension method. I'd just go ahead and copy the file into a new one with the appropriate name and extension, but we're talking about huge, uncompressed HD video files. Is there a way to utilize tPath2 with a File or FileInfo object that I'm missing?

I appreciate any assistance that anyone can give me here. Thanks.

like image 590
Rich Hoffman Avatar asked Oct 01 '10 16:10

Rich Hoffman


2 Answers

The Path class just allows you to perform manipulations on a file path (meaning the string) at a high level, not a file itself.

You'll need to use File.Move in order to rename a file (including just adding an extension).

string tPath = videoPath + videoName;
string tPath2 = Path.ChangeExtension(tPath, ".yuv");

File.Move(tPath, tPath2); //effectively changes the extension
like image 111
Adam Robinson Avatar answered Sep 23 '22 17:09

Adam Robinson


To carry out your rename without having to make a copy, add this line at the end:

System.IO.File.Move(tPath, tPath2);

(File.Move(src, dst) does the same thing that FileInfo.MoveTo(dst) does)

For your problem of files without an extension, try this:

if(string.IsNullOrEmpty(Path.GetExtension(tPath)){
  tPath += ".yuv";
}
like image 39
Andrew Barber Avatar answered Sep 23 '22 17:09

Andrew Barber