rename file by adding an incrementing number to old file name c# - c#

I'm writing my first Cocoa app in c#, its suppose to append/add numbers at the begging of a file name.
Users give only the path to the folder (for example with music), and for each file included in folder the program suppose to add incrementing numbers like
001_(old_fileName),
002_(old_fileName),
...,
092_(old_fileName)
etc,
Untill the end of files in given folder (by path).
There is no way to split a file name, cause file names are not known (may even include numbers itself). I've tried few possible options to solve this, but non of them works. Found few already asked question with changing names in c# but non of the results actually helped me.
The code under is the rest I've got at the moment, all non-working tries were firstly commented and later deleted. by NSAlert i see the path/name of each file in folder as a help. I would be more than happy to receive help
void RenameFunction()
{
string sPath = _Path_textBox.StringValue;
if (Directory.Exists(sPath))
{
var txtFiles = Directory.EnumerateFiles(sPath);
var txt2Files = Directory.GetFiles((sPath));
string fileNameOnly = Path.GetFileNameWithoutExtension(sPath);
string extension = Path.GetExtension(sPath);
string path = Path.GetDirectoryName(sPath);
string newFullPath = sPath;
int count = 1;
while (File.Exists(sPath))//newFullPath))
{
string tempFileName = string.Format(count + "_" + fileNameOnly + sPath);
//count++;
//string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
newFullPath = Path.Combine(path, extension + tempFileName);
count++;
}
string[] fileEntities = Directory.GetFiles(newFullPath); //GetFileSystemEntries(sPath);//GetFiles(sPath);
//foreach (var _songName in fileEntities)
//{
// string tempFileName = count + "_" + fileNameOnly + sPath;
// //string.Format("{0}{0}{0}{1}", fileNameOnly, count++);
// newFullPath = Path.Combine(sPath ,extension + tempFileName);
// File.Move(sPath, newFullPath);
//}
foreach (var _songName in fileEntities)
{
AmountofFiles(_songName);
}
}
}
void AmountofFiles(string path)
{
var alert2 = new NSAlert();
alert2.MessageText = "mp3";
alert2.InformativeText = "AMOUNT OF MP3 FILES IS '{1}' : " + path;
alert2.RunModal();
}

Have you try use File.Move? Just move file to same path, but another name
File.Move("NameToBeRename.jpg","NewName.jpg");

There are multiple things which are not right with the code you share. The thing which want to achieve can be implemented using very simple approach.
All you need to do is retrieve all the files names with the full path from the directory and rename them one by one.
Follow the below code which demonstrates the above mentioned approach.
// Path of the directory.
var directroy = _Path_textBox.StringValue;
if (Directory.Exists(directroy))
{
//Get all the filenames with full path from the directory.
var filePaths = Directory.EnumerateFiles(directroy);
//Variable to append number in front of the file name.
var count = 1;
//Iterate thru all the file names
foreach (var filePath in filePaths)
{
//Get only file name from the full file path.
var fileName = Path.GetFileName(filePath);
//Create new path with the directory path and new file name.
var destLocation = Path.Combine(directory, count + fileName);
//User File.Move to move file to the same directory with new name.
File.Move(filePath, destLocation);
//Increment count.
count++;
}
}
I hope this helps you to resolve your issue.

Related

Batch Moving files matching filenames to folders in C# or using a script

I was wondering if someone could assist or point me in the right direction to move files where part of the filename needs to be matched to part of the foldername for example:
Moving filename Cust-10598.txt to a folder named John-Doe-10598 Is this possible?
I was able to create all the folders inside the root directory where all the files are contained, now I would like to sort them and put each of them inside the matching folder.
Any help or ideas are highly appreciated
Assuming you already have a list of probably folders using Directory.GetDirectores(),
var listOfFolders = Directory.GetDirectories(basePath);
You can find the associated Folder for given filename using following method.
string GetAssociatedDirectory(string fileName,IEnumerable<string> folderNames)
{
Regex regEx = new Regex(#"Cust-(?<Id>[\d]*)",RegexOptions.Compiled);
Match match = regEx.Match(fileName);
if (match.Success)
{
var customerId = match.Groups["Id"].Value;
if(folderNames.Any(folder=>folder.EndsWith($"-{customerId}")))
{
return folderNames.First(folder=>folder.EndsWith(customerId));
}
else
{
throw new Exception("Folder not found");
}
}
throw new Exception("Invalid File Name");
}
You can then use File.Move to copy the file to destination directory
You could simply Split() on '-' if it's that simple of naming convention.
class Program
{
static void Main(string[] args)
{
var file = "Cust-10598.txt";
var fileSplit = file.Split('-');
var sourceDir = #"C:\";
var destFolder = "{name of destination folder}-" + Path.GetFileNameWithoutExtension(fileSplit[1]);
var destPath = #"C:\newpath";
File.Move(Path.Combine(source, file), Path.Combine(destPath, destFolder, file));
}
}

How to get files with desired name in C# using Directory.Getfile?

I am trying to obtain a file of name "fileName.wav" from the directory whose path has been specified im not able to get the desired function .. any help in this regard is appreciated.
static void Main(string[] args)
{
string[] fileEntries = Directory.GetFiles(
#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS", "*.wav");
foreach (string fileName in fileEntries)
{
string[] fileEntries1 = Directory.GetFiles(
#"D:\project\older versions\dpc_latest\Testing\DPCPlus\input");
foreach (string fileName1 in fileEntries1)
{
Console.WriteLine(Path.GetFileName(fileName1));
}
}
}
This Code will search for all .xml extension files with matches abCd name from C:\\SomeDir\\ folder.
string cCId ="abCd";
DirectoryInfo di = new DirectoryInfo("C:\\SomeDir\\");
FileInfo[] orderFiles = di.GetFiles("*" + cCId + "*.xml", SearchOption.TopDirectoryOnly);
You should change this code according to your needs.
Hope this helps you.
If you want to extract name and extension from a file-path, you can use following code:
string result = Path.GetFileName(yourFilePath); // result will be filename.wav
You can not use GetFiles method for a file path!
Directory.GetFiles(#"D:\project\Benten_lat\BentenPj_000_20141124_final\Testing\DPCPlus\Ref\Generated_Ref_Outputs_MSVS\filename.wav") //Error
The input for this method should be a directory!
Assumptions based on your question (please correct me if I am wrong):
You know the folder (e.g. the user entered it)
You know the file name (e.g. it is hard coded because it must be the same always)
In this case you do not really need to search the file.
Solution:
string folderPath = #"D:\somewhere";
string fileName = "file.wav";
string filePath = Path.Combine(folderPath, fileName);
if (File.Exists(filePath))
{
// continue reading the file, etc.
}
else
{
// handle file not found
}

place same file type in a folder

I am using Magick.NET and C# Console. The code below finds all the .eps file and then converting it to .jpg.
foreach (string fileName in Directory.GetFiles("C:/Users/Adrian/Documents/Visual Studio 2010/Projects/ImageMagickTest/ImageMagickTest/bin/Debug/eps","*.eps"))
{
using (MagickImage image = new MagickImage())
{
Console.WriteLine("\n\nNow Converting. Please Wait...\n\n");
image.Read(fileName, settings);
image.Write(fileName.Substring(0,fileName.Length - 3) + ".jpg");
i++;
Console.WriteLine("Conversion Success.\n\n");
Console.WriteLine("Files Converted: " + i);
}
}
Now, what I want is to separate .eps from .jpg.
for example:
folder /eps/ contents:
image1.eps
image2.eps
after executing the loop. the folder /eps/ contents will be:
image1.eps
image2.eps
image1.jpg
image2.jpg
How will i place the .jpg in a different folder?
I'm assuming you want a jpg folder? Add this to create the folder before your foreach loop.
if (!Directory.Exists("C:/Users/Adrian/Documents/Visual Studio 2010/Projects/ImageMagickTest/ImageMagickTest/bin/Debug/jpg"))
{
Directory.CreateDirectory("C:/Users/Adrian/Documents/Visual Studio 2010/Projects/ImageMagickTest/ImageMagickTest/bin/Debug/jpg");
}
I'm also assuming image.Write will actually create the file, if so then you can change the following line
image.Write(fileName.Substring(0,fileName.Length - 3) + ".jpg");
To be something like this
image.Write(fileName.Substring(0,fileName.Length - 7) + "jpg/.jpg");
I think This code will give you exactly what you want
foreach (string fileName in Directory.GetFiles("Folder","*.eps"))
{
using (MagickImage image = new MagickImage())
{
Console.WriteLine("\n\nNow Converting. Please Wait...\n\n");
image.Read(fileName, settings);
string[] split = filename.Split('\\');
string clear_file_name = split[split.Length-1];
string split_file_name= clear_file_name.split('.');
string filename_without_extention = split_file_name[0];
if(!Directory.Exists(folder+"\\jpeg"))
Directory.Create(folder+"\\jpeg");
image.Write(fileName.Substring(0,folder+"\\jpeg\\"+file_name_without_extention+".jpg");
i++;
Console.WriteLine("Conversion Success.\n\n");
Console.WriteLine("Files Converted: " + i);
}
}
E.g.
// Set the source folder to whatever.
var sourceFolderPath = "...";
// Create the destination folder path by removing the leaf folder name and replacing it with another.
var destinationFolderPath = Path.Combine(Path.GetDirectoryName(sourceFolderPath), "jpg");
foreach (var sourceFilePath in Directory.GetFiles(sourceFolderPath, "*.eps"))
{
// Build the destination file path from the desitination folder path, file name and a new extension.
var destinationFilePath = Path.ChangeExtension(Path.Combine(destinationFolderPath, Path.GetFileName(sourceFilePath)), ".jpg");
// Use destinationFilePath here.
}

How to copy a file to another path?

I need to copy a file to another path, leaving the original where it is.
I also want to be able to rename the file.
Will FileInfo's CopyTo method work?
Have a look at File.Copy()
Using File.Copy you can specify the new file name as part of the destination string.
So something like
File.Copy(#"c:\test.txt", #"c:\test\foo.txt");
See also How to: Copy, Delete, and Move Files and Folders (C# Programming Guide)
Yes. It will work: FileInfo.CopyTo Method
Use this method to allow or prevent overwriting of an existing file. Use the CopyTo method to prevent overwriting of an existing file by default.
All other responses are correct, but since you asked for FileInfo, here's a sample:
FileInfo fi = new FileInfo(#"c:\yourfile.ext");
fi.CopyTo(#"d:\anotherfile.ext", true); // existing file will be overwritten
I tried to copy an xml file from one location to another. Here is my code:
public void SaveStockInfoToAnotherFile()
{
string sourcePath = #"C:\inetpub\wwwroot";
string destinationPath = #"G:\ProjectBO\ForFutureAnalysis";
string sourceFileName = "startingStock.xml";
string destinationFileName = DateTime.Now.ToString("yyyyMMddhhmmss") + ".xml"; // Don't mind this. I did this because I needed to name the copied files with respect to time.
string sourceFile = System.IO.Path.Combine(sourcePath, sourceFileName);
string destinationFile = System.IO.Path.Combine(destinationPath, destinationFileName);
if (!System.IO.Directory.Exists(destinationPath))
{
System.IO.Directory.CreateDirectory(destinationPath);
}
System.IO.File.Copy(sourceFile, destinationFile, true);
}
Then I called this function inside a timer_elapsed function of certain interval which I think you don't need to see. It worked. Hope this helps.
You could also use File.Copy to copy and File.Move to rename it afterwords.
// Copy the file (specify true or false to overwrite or not overwrite the destination file if it exists.
File.Copy(mySourceFileAndPath, myDestinationFileAndPath, [true | false]);
// EDIT: as "astander" notes correctly, this step is not necessary, as File.Copy can rename already...
// However, this code could be adapted to rename the original file after copying
// Rename the file if the destination file doesn't exist. Throw exception otherwise
//if (!File.Exists(myRenamedDestinationFileAndPath))
// File.Move(myDestinationFileAndPath, myRenamedDestinationFileAndPath);
//else
// throw new IOException("Failed to rename file after copying, because destination file exists!");
EDIT
Commented out the "rename" code, because File.Copy can already copy and rename in one step, as astander noted correctly in the comments.
However, the rename code could be adapted if the OP desired to rename the source file after it has been copied to a new location.
string directoryPath = Path.GetDirectoryName(destinationFileName);
// If directory doesn't exist create one
if (!Directory.Exists(directoryPath))
{
DirectoryInfo di = Directory.CreateDirectory(directoryPath);
}
File.Copy(sourceFileName, destinationFileName);
File::Copy will copy the file to the destination folder and File::Move can both move and rename a file.
This is what I did to move a test file from the downloads to the desktop.
I hope its useful.
private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
{
string sourcePath = #"C:\Users\UsreName\Downloads";
string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
string[] shortcuts = {
"FileCopyTest.txt"};
try
{
listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
for (int i = 0; i < shortcuts.Length; i++)
{
if (shortcuts[i]!= null)
{
File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);
listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
}
else
{
listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
}
}
}
catch (Exception ex)
{
listbox1.Items.Add("Unable to Copy file. Error : " + ex);
}
}
TO Copy The Folder I Use Two Text Box To Know The Place Of Folder And Anther Text Box To Know What The Folder To Copy It And This Is The Code
MessageBox.Show("The File is Create in The Place Of The Programe If you Don't Write The Place Of copy And You write Only Name Of Folder");// It Is To Help The User TO Know
if (Fromtb.Text=="")
{
MessageBox.Show("Ples You Should Write All Text Box");
Fromtb.Select();
return;
}
else if (Nametb.Text == "")
{
MessageBox.Show("Ples You Should Write The Third Text Box");
Nametb.Select();
return;
}
else if (Totb.Text == "")
{
MessageBox.Show("Ples You Should Write The Second Text Box");
Totb.Select();
return;
}
string fileName = Nametb.Text;
string sourcePath = #"" + Fromtb.Text;
string targetPath = #"" + Totb.Text;
string sourceFile = System.IO.Path.Combine(sourcePath, fileName);
string destFile = System.IO.Path.Combine(targetPath, fileName);
if (!System.IO.Directory.Exists(targetPath))
{
System.IO.Directory.CreateDirectory(targetPath);
//when The User Write The New Folder It Will Create
MessageBox.Show("The File is Create in "+" "+Totb.Text);
}
System.IO.File.Copy(sourceFile, destFile, true);
if (System.IO.Directory.Exists(sourcePath))
{
string[] files = System.IO.Directory.GetFiles(sourcePath);
foreach (string s in files)
{
fileName = System.IO.Path.GetFileName(s);
destFile = System.IO.Path.Combine(targetPath, fileName);
System.IO.File.Copy(s, destFile, true);
}
MessageBox.Show("The File is copy To " + Totb.Text);
}
Old Question,but I would like to add complete Console Application example, considering you have files and proper permissions for the given folder, here is the code
class Program
{
static void Main(string[] args)
{
//path of file
string pathToOriginalFile = #"E:\C-sharp-IO\test.txt";
//duplicate file path
string PathForDuplicateFile = #"E:\C-sharp-IO\testDuplicate.txt";
//provide source and destination file paths
File.Copy(pathToOriginalFile, PathForDuplicateFile);
Console.ReadKey();
}
}
Source: File I/O in C# (Read, Write, Delete, Copy file using C#)
File.Move(#"c:\filename", #"c:\filenamet\filename.txt");

How can I create a temp file with a specific extension with .NET?

I need to generate a unique temporary file with a .csv extension.
What I do right now is
string filepath = System.IO.Path.GetTempFileName().Replace(".tmp", ".csv");
However, this doesn't guarantee that my .csv file will be unique.
I know the chances I ever got a collision are very low (especially if you consider that I don't delete the .tmp files), but this code doesn't looks good to me.
Of course I could manually generate random file names until I eventually find a unique one (which shouldn't be a problem), but I'm curious to know if others have found a nice way to deal with this problem.
Guaranteed to be (statistically) unique:
string fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
(To quote from the wiki article on the probabilty of a collision:
...one's annual risk of being hit by a
meteorite is estimated to be one
chance in 17 billion [19], that means
the probability is about 0.00000000006
(6 × 10−11), equivalent to the odds of
creating a few tens of trillions of
UUIDs in a year and having one
duplicate. In other words, only after
generating 1 billion UUIDs every
second for the next 100 years, the
probability of creating just one
duplicate would be about 50%. The
probability of one duplicate would be
about 50% if every person on earth
owns 600 million UUIDs
EDIT: Please also see JaredPar's comments.
Try this function ...
public static string GetTempFilePathWithExtension(string extension) {
var path = Path.GetTempPath();
var fileName = Path.ChangeExtension(Guid.NewGuid().ToString(), extension);
return Path.Combine(path, fileName);
}
It will return a full path with the extension of your choice.
Note, it's not guaranteed to produce a unique file name since someone else could have technically already created that file. However the chances of someone guessing the next guid produced by your app and creating it is very very low. It's pretty safe to assume this will be unique.
public static string GetTempFileName(string extension)
{
int attempt = 0;
while (true)
{
string fileName = Path.GetRandomFileName();
fileName = Path.ChangeExtension(fileName, extension);
fileName = Path.Combine(Path.GetTempPath(), fileName);
try
{
using (new FileStream(fileName, FileMode.CreateNew)) { }
return fileName;
}
catch (IOException ex)
{
if (++attempt == 10)
throw new IOException("No unique temporary file name is available.", ex);
}
}
}
Note: this works like Path.GetTempFileName. An empty file is created to reserve the file name. It makes 10 attempts, in case of collisions generated by Path.GetRandomFileName();
You can also alternatively use System.CodeDom.Compiler.TempFileCollection.
string tempDirectory = #"c:\\temp";
TempFileCollection coll = new TempFileCollection(tempDirectory, true);
string filename = coll.AddExtension("txt", true);
File.WriteAllText(Path.Combine(tempDirectory,filename),"Hello World");
Here I used a txt extension but you can specify whatever you want. I also set the keep flag to true so that the temp file is kept around after use. Unfortunately, TempFileCollection creates one random file per extension. If you need more temp files, you can create multiple instances of TempFileCollection.
The MSDN documentation for C++'s GetTempFileName discusses your concern and answers it:
GetTempFileName is not able to guarantee that the file name is unique.
Only the lower 16 bits of the uUnique parameter are used. This limits GetTempFileName to a maximum of 65,535 unique file names if the lpPathName and lpPrefixString parameters remain the same.
Due to the algorithm used to generate file names, GetTempFileName can perform poorly when creating a large number of files with the same prefix. In such cases, it is recommended that you construct unique file names based on GUIDs.
Why not checking if the file exists?
string fileName;
do
{
fileName = System.IO.Path.GetTempPath() + Guid.NewGuid().ToString() + ".csv";
} while (System.IO.File.Exists(fileName));
You can also do the following
string filepath = Path.ChangeExtension(Path.GetTempFileName(), ".csv");
and this also works as expected
string filepath = Path.ChangeExtension(Path.GetTempPath() + Guid.NewGuid().ToString(), ".csv");
How about:
Path.Combine(Path.GetTempPath(), DateTime.Now.Ticks.ToString() + "_" + Guid.NewGuid().ToString() + ".csv")
It is highly improbable that the computer will generate the same Guid at the same instant of time. The only weakness i see here is the performance impact DateTime.Now.Ticks will add.
In my opinion, most answers proposed here as sub-optimal. The one coming closest is the original one proposed initially by Brann.
A Temp Filename must be
Unique
Conflict-free (not already exist)
Atomic (Creation of Name & File in the same operation)
Hard to guess
Because of these requirements, it is not a godd idea to program such a beast on your own. Smart People writing IO Libraries worry about things like locking (if needed) etc.
Therefore, I see no need to rewrite System.IO.Path.GetTempFileName().
This, even if it looks clumsy, should do the job:
//Note that this already *creates* the file
string filename1 = System.IO.Path.GetTempFileName()
// Rename and move
filename = filename.Replace(".tmp", ".csv");
File.Move(filename1 , filename);
I mixed #Maxence and #Mitch Wheat answers keeping in mind I want the semantic of GetTempFileName method (the fileName is the name of a new file created) adding the extension preferred.
string GetNewTempFile(string extension)
{
if (!extension.StartWith(".")) extension="." + extension;
string fileName;
bool bCollisions = false;
do {
fileName = Path.Combine(System.IO.Path.GetTempPath(), Guid.NewGuid().ToString() + extension);
try
{
using (new FileStream(fileName, FileMode.CreateNew)) { }
bCollisions = false;
}
catch (IOException)
{
bCollisions = true;
}
}
while (bCollisions);
return fileName;
}
This could be handy for you... It's to create a temp. folder and return it as a string in VB.NET.
Easily convertible to C#:
Public Function GetTempDirectory() As String
Dim mpath As String
Do
mpath = System.IO.Path.Combine(System.IO.Path.GetTempPath, System.IO.Path.GetRandomFileName)
Loop While System.IO.Directory.Exists(mpath) Or System.IO.File.Exists(mpath)
System.IO.Directory.CreateDirectory(mpath)
Return mpath
End Function
This seems to work fine for me: it checks for file existance and creates the file to be sure it's a writable location.
Should work fine, you can change it to return directly the FileStream (which is normally what you need for a temp file):
private string GetTempFile(string fileExtension)
{
string temp = System.IO.Path.GetTempPath();
string res = string.Empty;
while (true) {
res = string.Format("{0}.{1}", Guid.NewGuid().ToString(), fileExtension);
res = System.IO.Path.Combine(temp, res);
if (!System.IO.File.Exists(res)) {
try {
System.IO.FileStream s = System.IO.File.Create(res);
s.Close();
break;
}
catch (Exception) {
}
}
}
return res;
} // GetTempFile
Based on answers I found from the internet, I come to my code as following:
public static string GetTemporaryFileName()
{
string tempFilePath = Path.Combine(Path.GetTempPath(), "SnapshotTemp");
Directory.Delete(tempFilePath, true);
Directory.CreateDirectory(tempFilePath);
return Path.Combine(tempFilePath, DateTime.Now.ToString("MMddHHmm") + "-" + Guid.NewGuid().ToString() + ".png");
}
And as C# Cookbook by Jay Hilyard, Stephen Teilhet pointed in Using a Temporary File in Your Application:
you should use a temporary file whenever you need to store
information temporarily for later retrieval.
The one thing you must remember is to delete this temporary file
before the application that created it is terminated.
If it is not deleted, it will remain in the user’s temporary
directory until the user manually deletes it.
This is what I am doing:
string tStamp = String.Format("{0:yyyyMMdd.HHmmss}", DateTime.Now);
string ProcID = Process.GetCurrentProcess().Id.ToString();
string tmpFolder = System.IO.Path.GetTempPath();
string outFile = tmpFolder + ProcID + "_" + tStamp + ".txt";
This is a simple but effective way to generate incremental filenames. It will look in the current directly (you can easily point that somewhere else) and search for files with the base YourApplicationName*.txt (again you can easily change that). It will start at 0000 so that the first file name will be YourApplicationName0000.txt. if for some reason there are file names with junk between (meaning not numbers) the left and right parts, those files will be ignored by virtue of the tryparse call.
public static string CreateNewOutPutFile()
{
const string RemoveLeft = "YourApplicationName";
const string RemoveRight = ".txt";
const string searchString = RemoveLeft + "*" + RemoveRight;
const string numberSpecifier = "0000";
int maxTempNdx = -1;
string fileName;
string [] Files = Directory.GetFiles(Directory.GetCurrentDirectory(), searchString);
foreach( string file in Files)
{
fileName = Path.GetFileName(file);
string stripped = fileName.Remove(fileName.Length - RemoveRight.Length, RemoveRight.Length).Remove(0, RemoveLeft.Length);
if( int.TryParse(stripped,out int current) )
{
if (current > maxTempNdx)
maxTempNdx = current;
}
}
maxTempNdx++;
fileName = RemoveLeft + maxTempNdx.ToString(numberSpecifier) + RemoveRight;
File.CreateText(fileName); // optional
return fileName;
}
Easy Function in C#:
public static string GetTempFileName(string extension = "csv")
{
return Path.ChangeExtension(Path.GetTempFileName(), extension);
}
In this what we can do we can first find the extension of file
which is coming from file and after finding its extension.Then we
can create the temprary name of file and after that we can change
extension by the previous one it will works.
var name = Path.GetTempFileName();
var changename = Path.GetFileName(name);
var fileName = Path.ChangeExtension(changename, fileExtension);
I think you should try this:
string path = Path.GetRandomFileName();
path = Path.Combine(#"c:\temp", path);
path = Path.ChangeExtension(path, ".tmp");
File.Create(path);
It generates a unique filename and creates a file with that file name at a specified location.

Categories

Resources