Related
I am trying to make an app that will verify multiple file hashes at once. The way I've done it is like this: Hash source files from location 1 and output to a textbox filename, hash type and the hash itself.
Hash source files from location 2 and output to another text box the second filename, hash type and hash.
The problem is that that the paths are different, and there are several hashes to verify. I don't know how to split the string to make this work so that just the hashes get checked against the other hashes, without filesnames.
This is how I am getting the hash string:
string[] files = filePicketTextBox.Text.Split('\n');
if (files.Length > 0)
{
foreach (var file in files).. //do hash
Here is how the output of the hash gets done:
output = file + " MD5 Hash = " + sb.ToString() + "\n";
Here's what it looks like in the output textbox:
C:\Users\jj\Downloads\hasher.zip MD5 Hash = 8B0A222D30CA4962AFE30511695C8BB3
C:\Users\jj\Downloads\OfficeSetup.exe MD5 Hash = 2E210D07A9AE9B93FAEB0852A0DAFF83
And here's what I'm using to verify the hashes:
private void VerifyHashes(object sender, RoutedEventArgs e)
{
string output_one = outputTextBox.Text;
string output_two = output2TextBox.Text;
if (output_one == output_two)
{
Verification.Text = "HASHES VERIFIED";
}
else
{
Verification.Text = "NO MATCH";
}
Can anyone help me with how to split this to remove those filenames and take into account that multiple filenames will be getting verified at once?
Full code:
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
// Create the CommonOpenFIleDialog object
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = false;
dialog.Multiselect = true;
// Check to see if we have a result
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
filePicketTextBox.Text = string.Join("\n", dialog.FileNames);
}
else
{
outputTextBox.Text = "Operation cancelled." + "\n";
}
}
private async void runButton_Click(object sender, RoutedEventArgs e)
{
File.Delete(Path.Combine(Environment.CurrentDirectory, "log.txt"));
// Detect and handle the event of a void filename
if (filePicketTextBox.Text == "")
{
outputTextBox.Text = "No file selected." + "\n";
return;
}
string[] files = filePicketTextBox.Text.Split('\n');
if (files.Length > 0)
{
foreach (var file in files)
{
// Detect and handle the event of a non-valid filename
try
{
var stream = File.OpenRead(file);
stream.Close();
}
catch
{
outputTextBox.Text = "Invalid filename." + "\n";
return;
}
// Detect event of no options selected
if (!(bool)md5CheckBox.IsChecked && !(bool)sha1CheckBox.IsChecked && !(bool)sha256CheckBox.IsChecked && !(bool)sha512CheckBox.IsChecked)
{
outputTextBox.Text = "No hash algorithm selected.";
}
// MD5 Calculation and Display
if ((bool)md5CheckBox.IsChecked)
{
await Task.Run(() =>
{
var result = checkMD5(file).Result;
WriteIntoTxtBox(result);
});
await Task.Delay(1000);
progressbar.Value = 0;
}
MD5 Calc code:
public async Task<string> checkMD5(string file)
{
string output;
using (var md5 = MD5.Create())
{
AddValueLoadingBar(20, true);
using (var stream = File.OpenRead(file))
{
byte[] hash = md5.ComputeHash(stream);
AddValueLoadingBar(60, true);
await Task.Delay(1000);
StringBuilder sb = new StringBuilder(hash.Length);
int toAdd = 30 / hash.Length;
foreach (byte b in hash)
{
sb.AppendFormat("{0:X2}", b);
AddValueLoadingBar(toAdd);
}
output = file + " MD5 Hash = " + sb.ToString() + "\n";
AddValueLoadingBar(100, true);
}
}
return output;
}
this works fine:
string[] Files = strFileBuf.Split('\n');
string[] MyDelim = { " MD5 Hash = " };
foreach (string OneRow in Files)
{
string[] TwoParts = OneRow.Split(MyDelim,StringSplitOptions.None);
string FileNameOnly = Path.GetFileName(TwoParts[0]);
string MyHash = TwoParts[1];
TextBox1.Text += ("File = " + FileNameOnly + " ->Hash = " + MyHash + "\n");
}
Output:
So, you can split on the each line (\n)
And then you can assume that the delimiter is the string part inbetween.
So, we split out to file name, and hash.
and then i display ONLY file name (without path) and the hash code.
***EDIT **************************************
Ok, the user wants the output sorted. They should have posted SOME mark up.
Here what we will do:
We assume TWO input strings - the from files, the "to" files.
As noted, I REALLY have to assume that some kind of list or something MUCH better then two strings are the SOURCE of these two file sets.
However, the code that follows could WELL be adapted - and be run directly off the original two "lists" of files.
These two strings - from a text box, from the bottom of the ocean - don't care.
So, we assume this markup on the page:
<asp:Button ID="Button1" runat="server" Height="31px" Text="Button" Width="110px" />
<br />
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
<br />
A simple button, and a simple gridView.
We will shove/send the results out to the Grid view - sorted.
The code would/could behind the above button could/would look like this:
protected void Button1_Click(object sender, EventArgs e)
{
string strFileBuf1 = ""; ' set this from/input files string
string strFileBuf2 = ""; ' set this to files string
SortedDictionary<string, string> Loc1Files;
SortedDictionary<string, string> Loc2Files;
Loc1Files = GetFiles(strFileBuf1);
Loc2Files = GetFiles(strFileBuf2);
DataTable MyTable = new DataTable();
MyTable.Columns.Add("FromFile", typeof(string));
MyTable.Columns.Add("ToFile", typeof(string));
MyTable.Columns.Add("Match", typeof(string));
foreach (KeyValuePair<string, string> OneFile in Loc1Files)
{
DataRow OneRow;
OneRow = MyTable.Rows.Add;
OneRow("FromFile") = OneFile.Key;
if (Loc2Files.ContainsKey(OneFile.Key))
{
OneRow("ToFile") = OneFile.Key;
// compare hash codes
if (OneFile.Value == Loc2Files[OneFile.Key])
OneRow("Match") = "Yes";
else
OneRow("Match") = "No";
}
else
{
OneRow("ToFile") = "missing";
OneRow("Match") = "missing";
}
}
GridView1.DataSource = MyTable;
GridView1.DataBind();
}
Output:
The function/sub that splits out the data and returns that sorted dict list is this - we assume those "two" sets of files as those strings.
public SortedDictionary<string, string> GetFiles(string str)
{
string[] Files = str.Split('\n');
SortedDictionary<string, string> MyList = new SortedDictionary<string, string>();
foreach (string OneRow in Files)
{
string[] MyDelim = { " MD5 Hash = " };
string[] TwoParts = OneRow.Split(MyDelim,StringSplitOptions.None);
MyList.Add(Path.GetFileName(TwoParts[0]), TwoParts[1]);
}
return MyList;
}
I've done quite a bit of work to reduce your code down to the bare essentials of computing your hashes without relying on the UI. I've then got the code that requires the UI separated out so that it has nothing to do with computing hashes.
To start with I created a single hashing function that you can use to compute any hash.
public Task<string> ComputeHash(string file, Func<HashAlgorithm> create)
{
return Task.Run(() =>
{
using (var crypto = create())
{
using (var stream = File.OpenRead(file))
{
return String.Concat(
crypto.ComputeHash(stream).Select(x => x.ToString("X2")));
}
}
});
}
I've now created two fields to store the list of files and the resulting hashes.
private string[] _fileNames = null;
private string[] _hashes = null;
I'll show the code that sets the _fileNames array later, but for now this is the code that you can call to compute your hashes:
private async Task<String> Run(bool md5, bool sha1, bool sha256, bool sha512)
{
File.Delete(Path.Combine(Environment.CurrentDirectory, "log.txt"));
Func<HashAlgorithm> hashAlgorithm = null;
if (md5) hashAlgorithm = () => MD5.Create();
else if (sha1) hashAlgorithm = () => SHA1.Create();
else if (sha256) hashAlgorithm = () => SHA256.Create();
else if (sha512) hashAlgorithm = () => SHA512.Create();
if (hashAlgorithm == null)
{
return "No hash algorithm selected.";
}
else if (_fileNames == null || _fileNames.Length == 0)
{
return "No file selected." + "\n";
}
else if (_fileNames.Any(f => !File.Exists(f)))
{
return "Invalid filename." + "\n";
}
else
{
var tasks = _fileNames.Select(f => ComputeHash(f, hashAlgorithm)).ToArray();
_hashes = await Task.WhenAll(tasks);
return "Success";
}
}
The hardest part of this code, in my opinion, is the use of Func<HashAlgorithm> hashAlgorithm to store the hashing algorithm. If you're not familiar with a Func<> then it's worth looking up, but think of it as a way to store a function in a variable so that you can call the function later.
Now, finally, we have the two bits of code that interact with the UI:
private void filePickerButton_Click(object sender, RoutedEventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.InitialDirectory = "C:\\Users";
dialog.IsFolderPicker = false;
dialog.Multiselect = true;
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
_fileNames = dialog.FileNames.ToArray();
filePicketTextBox.Text = string.Join("\n", dialog.FileNames);
}
else
{
outputTextBox.Text = "Operation cancelled." + "\n";
}
}
private async void runButton_Click(object sender, RoutedEventArgs e)
{
string result = await Run(
md5CheckBox.IsChecked,
sha1CheckBox.IsChecked,
sha256CheckBox.IsChecked,
sha512CheckBox.IsChecked);
outputTextBox.Text = result;
}
The end result is that you have two arrays, _fileNames & _hashes that you can use to get the hash for each file name. No need for splitting text.
You should format your output with some delimiter other than a space as file names can have space in them, otherwise you will need to account for that.
Your solution is quite awkward and could certainly be reengineered for a better solution.
But to directly answer your question you can join your output into a Dictionary<string,string>
where the key would be the file name and value would the hash
var d1 = outputTextBox.Text.Split(Environment.NewLine.ToCharArray())
.Select(x => x.Split(' '))
.ToDictionary(
// use the file name without the directory as the key.
x => System.IO.Path.GetFileName(string.Join(" ", x.Take(x.Length - 4))),
// the has will be the last sequence of characters following the last space
x => x[x.Length - 1]
);
var d2 = output2TextBox.Text.Split(Environment.NewLine.ToCharArray())
.Select(x => x.Split(' '))
.ToDictionary(
// use the file name without the directory as the key.
x => System.IO.Path.GetFileName(string.Join(" ", x.Take(x.Length - 4))),
// the has will be the last sequence of characters following the last space
x => x[x.Length - 1]
);
After you would need to compare the contents of the two dictionaries using the file names as a key.
This can be done as follows
///compare the the keys of the two dictionaries match.
var areEqual = d1.Keys
.OrderBy(x=> x) // sort the first dictionaries keys
// comare the sorted keys to the sorted keys of the second dictionary
.SequenceEqual(d2.Keys.OrderBy(x=>x));
if (areEqual)
{
// if the keys match, then compare the hashes
areEqual = d1.Select(x => x.Value == d2[x.Key])
.All(x => x == true);
}
Now if you are only concerned with if the files in two directories match, you could just collect the hashes and compare them.
var outputTextBox = new TextBox();
var output2TextBox = new TextBox();
var hashes_left = outputTextBox.Text
.Split(Environment.NewLine.ToCharArray())
.Select(x => x.Substring(x.LastIndexOf(' ') + 1))
.OrderBy(x => x);
var hashes_right = output2TextBox.Text
.Split(Environment.NewLine.ToCharArray())
.Select(x => x.Substring(x.LastIndexOf(' ') + 1))
.OrderBy(x => x);
var areEqual = hashes_left.SequenceEqual(hashes_right);
However, even with these direct answers the proper thing would be to reengineer your code for a more efficient solution, such using a custom class in which you could use to compare strongly typed items in memory.
To clarify, reengineering the solution properly using custom classes would look something like this:
public class FileCollectionComparer
{
private HashAlgo algo;
private string[] x;
private string[] y;
public FileCollectionComparer(HashAlgo hashAlgo, string[] x, string[] y)
{
this.algo = hashAlgo;
this.x = x.OrderBy(z=> Path.GetFileName(z)).ToArray();
this.y = y.OrderBy(z => Path.GetFileName(z)).ToArray();
}
public bool AreEqual()
{
if (x.Length != y.Length)
return false;
else if (!x.Select(z=> Path.GetFileName(z))
.SequenceEqual(y.Select(z=> Path.GetFileName(z))))
return false;
else
{
var a = x.GetEnumerator();
var b = y.GetEnumerator();
while (a.MoveNext())
{
b.MoveNext()
var xHash = Hasher.GetHash((string)a.Current, algo);
var yHash = Hasher.GetHash((string)b.Current, algo);
if (xHash != yHash)
return false;
}
}
return true;
}
}
And we might define the HashAlgo enum and Hasher as:
public enum HashAlgo
{
MD5,
SHA1,
SHA256,
SHA512
}
public class Hasher
{
public static string GetHash(string filePath, HashAlgo algo)
{
HashAlgorithm hasher = null;
switch (algo)
{
case HashAlgo.MD5:
hasher = MD5.Create();
break;
case HashAlgo.SHA1:
hasher = SHA1.Create();
break;
case HashAlgo.SHA256:
hasher = SHA256.Create();
break;
case HashAlgo.SHA512:
hasher = SHA512.Create();
break;
default:
throw new InvalidEnumArgumentException(nameof(algo), (int)algo, typeof(HashAlgo));
}
using (var fs = File.OpenRead(filePath))
return string.Join("", hasher.ComputeHash(fs).Select(x => x.ToString("X2")));
}
}
Ok, it was as simple as adding this line in the hash method.
file = Path.GetFileName(file);
Here it is inside the method.
public async Task<string> checkMD5(string file)
{
string output;
using (var md5 = MD5.Create())
{
AddValueLoadingBar(20, true);
using (var stream = File.OpenRead(file))
{
byte[] hash = md5.ComputeHash(stream);
AddValueLoadingBar(60, true);
await Task.Delay(1000);
StringBuilder sb = new StringBuilder(hash.Length);
int toAdd = 30 / hash.Length;
foreach (byte b in hash)
{
sb.AppendFormat("{0:X2}", b);
AddValueLoadingBar(toAdd);
}
file = Path.GetFileName(file);
output = file + " MD5 Hash = " + sb.ToString() + "\n";
AddValueLoadingBar(100, true);
}
}
return output;
I added this right before the output, causing the output to not include the full path name which is the only thing that changes between the textboxes assuming the hashes are the same. The file name is the same, and if the hash is too, then it's verified.
This caused a lot of work but the answer was quite simple. My code definitely needs some re-writing though :) thanks everyone who answered this.
What i am attempting to do is read a .txt file which is structured like:
#signup.php|register.php
URL_1
#...
URL_2
I am trying to search the source code of a page, if it finds a value from URL_1 in the source code it will return to me what that value found was.
To read the .txt file i have this so far:
public static Dictionary<string, string> ReadAiFields(string path)
{
var values = new Dictionary<string, string>();
try
{
if (!File.Exists(path)) return values;
var lines = File.ReadAllLines(path);
for (var i = 0; i < lines.Length - 1; i++)
{
string line = lines[i];
if (line.StartsWith("#"))
{
string[] keys = line.Remove(0, 1).Split('|');
string value = lines[i + 1];
foreach (string key in keys)
{
if (!values.ContainsKey(key))
{
values.Add(key, value);
}
}
}
}
}
catch (Exception ex)
{
DebugLogging("[" + DateTime.Now + "]-[" + ex.ToString() + "]");
}
return values;
}
So in the source code if signup.php is found it will return it.
I have started to write:
public static string GetUrlStructureFromFile(string inputHtml)
{
string returnValue = "";
inputValue = inputHtml.ToLower();
var values = ReadAiFields(#"LogicFiles\rj-ai-url.txt");
var foundKey = values.Keys.FirstOrDefault(key => inputHtml.Contains(key));
if (foundKey != null)
{
returnValue = values[foundKey];
}
return returnValue;
}
This return the key URL_1 but i really need the value, i never wrote the original code which is why i'm unsure, any tips or help would be appreciated.
I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way.
For example, if I have this FileInfo
var file = new FileInfo(#"C:\file.ext");
I would like the method to give me a new FileInfo with C:\file 1.ext if C:\file.ext
existed, and C:\file 2.ext if C:\file 1.ext existed and so on. Something like this:
public FileInfo MakeUnique(FileInfo fileInfo)
{
if(fileInfo == null)
throw new ArgumentNullException("fileInfo");
if(!fileInfo.Exists)
return fileInfo;
// Somehow construct new filename from the one we have, test it,
// then do it again if necessary.
}
public FileInfo MakeUnique(string path)
{
string dir = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string fileExt = Path.GetExtension(path);
for (int i = 1; ;++i) {
if (!File.Exists(path))
return new FileInfo(path);
path = Path.Combine(dir, fileName + " " + i + fileExt);
}
}
Obviously, this is vulnerable to race conditions as noted in other answers.
Lots of good advice here. I ended up using a method written by Marc in an answer to a different question. Reformatted it a tiny bit and added another method to make it a bit easier to use "from the outside". Here is the result:
private static string numberPattern = " ({0})";
public static string NextAvailableFilename(string path)
{
// Short-cut if already available
if (!File.Exists(path))
return path;
// If path has extension then insert the number pattern just before the extension and return next filename
if (Path.HasExtension(path))
return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));
// Otherwise just append the pattern to the path and return next filename
return GetNextFilename(path + numberPattern);
}
private static string GetNextFilename(string pattern)
{
string tmp = string.Format(pattern, 1);
if (tmp == pattern)
throw new ArgumentException("The pattern must include an index place-holder", "pattern");
if (!File.Exists(tmp))
return tmp; // short-circuit if no matches
int min = 1, max = 2; // min is inclusive, max is exclusive/untested
while (File.Exists(string.Format(pattern, max)))
{
min = max;
max *= 2;
}
while (max != min + 1)
{
int pivot = (max + min) / 2;
if (File.Exists(string.Format(pattern, pivot)))
min = pivot;
else
max = pivot;
}
return string.Format(pattern, max);
}
Only partially tested it so far, but will update if I find any bugs with it. (Marcs code works nicely!) If you find any problems with it, please comment or edit or something :)
Not pretty, but I've had this for a while :
private string getNextFileName(string fileName)
{
string extension = Path.GetExtension(fileName);
int i = 0;
while (File.Exists(fileName))
{
if (i == 0)
fileName = fileName.Replace(extension, "(" + ++i + ")" + extension);
else
fileName = fileName.Replace("(" + i + ")" + extension, "(" + ++i + ")" + extension);
}
return fileName;
}
Assuming the files already exist:
File.txt
File(1).txt
File(2).txt
the call getNextFileName("File.txt") will return "File(3).txt".
Not the most efficient because it doesn't use binary search, but should be ok for small file count. And it doesn't take race condition into account...
If checking if the file exists is too hard you can always just add a date and time to the file name to make it unique:
FileName.YYYYMMDD.HHMMSS
Maybe even add milliseconds if necessary.
If the format doesn't bother you then you can call:
try{
string tempFile=System.IO.Path.GetTempFileName();
string file=System.IO.Path.GetFileName(tempFile);
//use file
System.IO.File.Delete(tempFile);
}catch(IOException ioe){
//handle
}catch(FileIOPermission fp){
//handle
}
PS:- Please read more about this at msdn before using.
/// <summary>
/// Create a unique filename for the given filename
/// </summary>
/// <param name="filename">A full filename, e.g., C:\temp\myfile.tmp</param>
/// <returns>A filename like C:\temp\myfile633822247336197902.tmp</returns>
public string GetUniqueFilename(string filename)
{
string basename = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename));
string uniquefilename = string.Format("{0}{1}{2}",
basename,
DateTime.Now.Ticks,
Path.GetExtension(filename));
// Thread.Sleep(1); // To really prevent collisions, but usually not needed
return uniquefilename;
}
As DateTime.Ticks has a resolution of 100 nanoseconds, collisions are extremely unlikely. However, a Thread.Sleep(1) will ensure that, but I doubt that it's needed
Insert a new GUID into the file name.
I must throw my 2-cents in. This is how I did it and it works for my use.
private static string IterateFileName(string fileName)
{
if (!File.Exists(fileName)) return fileName;
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
string name = fi.FullName.Substring(0, fi.FullName.Length - ext.Length);
int i = 2;
while (File.Exists($"{name}_{i}{ext}"))
{
i++;
}
return $"{name}_{i}{ext}";
}
The idea is to get a list of the existing files, parse out the numbers, then make the next highest one.
Note: This is vulnerable to race conditions, so if you have more than one thread creating these files, be careful.
Note 2: This is untested.
public static FileInfo GetNextUniqueFile(string path)
{
//if the given file doesn't exist, we're done
if(!File.Exists(path))
return new FileInfo(path);
//split the path into parts
string dirName = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string fileExt = Path.GetExtension(path);
//get the directory
DirectoryInfo dir = new DirectoryInfo(dir);
//get the list of existing files for this name and extension
var existingFiles = dir.GetFiles(Path.ChangeExtension(fileName + " *", fileExt);
//get the number strings from the existing files
var NumberStrings = from file in existingFiles
select Path.GetFileNameWithoutExtension(file.Name)
.Remove(0, fileName.Length /*we remove the space too*/);
//find the highest existing number
int highestNumber = 0;
foreach(var numberString in NumberStrings)
{
int tempNum;
if(Int32.TryParse(numberString, out tempnum) && tempNum > highestNumber)
highestNumber = tempNum;
}
//make the new FileInfo object
string newFileName = fileName + " " + (highestNumber + 1).ToString();
newFileName = Path.ChangeExtension(fileName, fileExt);
return new FileInfo(Path.Combine(dirName, newFileName));
}
Instead of poking the disk a number of times to find out if it has a particular variant of the desired file name, you could ask for the list of files that already exist and find the first gap according to your algorithm.
public static class FileInfoExtensions
{
public static FileInfo MakeUnique(this FileInfo fileInfo)
{
if (fileInfo == null)
{
throw new ArgumentNullException("fileInfo");
}
string newfileName = new FileUtilities().GetNextFileName(fileInfo.FullName);
return new FileInfo(newfileName);
}
}
public class FileUtilities
{
public string GetNextFileName(string fullFileName)
{
if (fullFileName == null)
{
throw new ArgumentNullException("fullFileName");
}
if (!File.Exists(fullFileName))
{
return fullFileName;
}
string baseFileName = Path.GetFileNameWithoutExtension(fullFileName);
string ext = Path.GetExtension(fullFileName);
string filePath = Path.GetDirectoryName(fullFileName);
var numbersUsed = Directory.GetFiles(filePath, baseFileName + "*" + ext)
.Select(x => Path.GetFileNameWithoutExtension(x).Substring(baseFileName.Length))
.Select(x =>
{
int result;
return Int32.TryParse(x, out result) ? result : 0;
})
.Distinct()
.OrderBy(x => x)
.ToList();
var firstGap = numbersUsed
.Select((x, i) => new { Index = i, Item = x })
.FirstOrDefault(x => x.Index != x.Item);
int numberToUse = firstGap != null ? firstGap.Item : numbersUsed.Count;
return Path.Combine(filePath, baseFileName) + numberToUse + ext;
}
}
Here's one that decouples the numbered naming question from the check of the filesystem:
/// <summary>
/// Finds the next unused unique (numbered) filename.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="inUse">Function that will determine if the name is already in use</param>
/// <returns>The original filename if it wasn't already used, or the filename with " (n)"
/// added to the name if the original filename is already in use.</returns>
private static string NextUniqueFilename(string fileName, Func<string, bool> inUse)
{
if (!inUse(fileName))
{
// this filename has not been seen before, return it unmodified
return fileName;
}
// this filename is already in use, add " (n)" to the end
var name = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
if (name == null)
{
throw new Exception("File name without extension returned null.");
}
const int max = 9999;
for (var i = 1; i < max; i++)
{
var nextUniqueFilename = string.Format("{0} ({1}){2}", name, i, extension);
if (!inUse(nextUniqueFilename))
{
return nextUniqueFilename;
}
}
throw new Exception(string.Format("Too many files by this name. Limit: {0}", max));
}
And here's how you might call it if you are using the filesystem
var safeName = NextUniqueFilename(filename, f => File.Exists(Path.Combine(folder, f)));
private async Task<CloudBlockBlob> CreateBlockBlob(CloudBlobContainer container, string blobNameToCreate)
{
var blockBlob = container.GetBlockBlobReference(blobNameToCreate);
var i = 1;
while (await blockBlob.ExistsAsync())
{
var newBlobNameToCreate = CreateRandomFileName(blobNameToCreate,i.ToString());
blockBlob = container.GetBlockBlobReference(newBlobNameToCreate);
i++;
}
return blockBlob;
}
private string CreateRandomFileName(string fileNameWithExtension, string prefix=null)
{
int fileExtPos = fileNameWithExtension.LastIndexOf(".", StringComparison.Ordinal);
if (fileExtPos >= 0)
{
var ext = fileNameWithExtension.Substring(fileExtPos, fileNameWithExtension.Length - fileExtPos);
var fileName = fileNameWithExtension.Substring(0, fileExtPos);
return String.Format("{0}_{1}{2}", fileName, String.IsNullOrWhiteSpace(prefix) ? new Random().Next(int.MinValue, int.MaxValue).ToString():prefix,ext);
}
//This means there is no Extension for the file and its fine attaching random number at the end.
return String.Format("{0}_{1}", fileNameWithExtension, new Random().Next(int.MinValue, int.MaxValue));
}
I use this code to create a consecutive _1,_2,_3 etc.. file name everytime a file exists in the blob storage.
Hope this self iterating function may help. It works fine for me.
public string getUniqueFileName(int i, string filepath, string filename)
{
string path = Path.Combine(filepath, filename);
if (System.IO.File.Exists(path))
{
string name = Path.GetFileNameWithoutExtension(filename);
string ext = Path.GetExtension(filename);
i++;
filename = getUniqueFileName(i, filepath, name + "_" + i + ext);
}
return filename;
}
This is an answer to question in this Link, but they marked it as a duplicate, so I post my answer here.
I created this proof of concept class (may contain bugs).
More explanation in code comments.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main( string[] args )
{
var testFilePaths = new List<string>
{
#"c:\test\file.txt",
#"c:\test\file(1).txt",
#"c:\test\file(2).txt",
#"c:\TEST2\file(3).txt",
#"c:\test\file(5).txt",
#"c:\test\file(5)abc.txt",
#"c:\test\file(5).avi"
};
// inspect in debbuger for correct values
var withSuffix = new DecomposedFilePath( "c:\\files\\file(13).txt");
var withoutSuffix = new DecomposedFilePath( "c:\\files\\file(abc).txt");
var withExtraNumber = new DecomposedFilePath( "c:\\files\\file(34)xyz(35).txt"); // "(34)" in the middle should be ignored
DecomposedFilePath changedSuffix = withExtraNumber.ReplaceSuffix( 1999 ); // "file(34)xyz(35).txt" -> "file(34)xyz(1999).txt"
DecomposedFilePath removedSuffix = changedSuffix.ReplaceSuffix( null ); // "file(34)xyz(1999).txt" -> "file(34)xyz.txt"
var testPath = new DecomposedFilePath( "c:\\test\\file.txt");
DecomposedFilePath nextPath1 = testPath.GetFirstFreeFilePath( testFilePaths );
// update our list
testFilePaths.Add( nextPath1.FullFilePath );
DecomposedFilePath nextPath2 = testPath.GetFirstFreeFilePath( testFilePaths );
testFilePaths.Add( nextPath2.FullFilePath );
DecomposedFilePath nextPath3 = testPath.GetFirstFreeFilePath( testFilePaths );
}
}
public sealed class DecomposedFilePath
{
public DecomposedFilePath( string filePath )
{
FullFilePath = Path.GetFullPath( filePath );
}
// "c:\myfiles\file(4).txt"
public string FullFilePath { get; }
// "file" or "file(1)"
public string FileNameWithoutExt => Path.GetFileNameWithoutExtension( FullFilePath );
// "file(13)" -> "file"
public string FileNameWithoutExtAndSuffix => FileNameWithoutExt.Substring( 0, FileNameWithoutExt.Length - Suffix.Length ); // removes suffix
// ".txt"
public string Extenstion => Path.GetExtension( FullFilePath );
// "c:\myfiles"
public string DirectoryPath => Path.GetDirectoryName( FullFilePath );
// "file(23)" -> "23", file -> stirng.Empty
public string Suffix
{
get
{
// we want to extract suffix from file name, e.g. "(34)" from "file(34)"
// I am not good at regex, but I hope it will work correctly
var regex = new Regex( #"\([0-9]+\)$" );
Match match = regex.Match( FileNameWithoutExt );
if (!match.Success) return string.Empty; // suffix not found
return match.Value; // return "(number)"
}
}
// tranlates suffix "(33)" to 33. If suffix is does not exist (string.empty), returns null (int?)
public int? SuffixAsInt
{
get
{
if (Suffix == string.Empty) return null;
string numberOnly = Suffix.Substring( 1, Suffix.Length - 2 ); // remove '(' from beginning and ')' from end
return int.Parse( numberOnly );
}
}
// e.g. input is suffix: 56 then it changes file name from "file(34)" to "file(56)"
public DecomposedFilePath ReplaceSuffix( int? suffix ) // null - removes suffix
{
string strSuffix = suffix is null ? string.Empty : $"({suffix})"; // add ( and )
string path = Path.Combine( DirectoryPath, FileNameWithoutExtAndSuffix + strSuffix + Extenstion ); // build full path
return new DecomposedFilePath( path );
}
public DecomposedFilePath GetFirstFreeFilePath( IEnumerable<string> filesInDir )
{
var decomposed = filesInDir
// convert all paths to our class
.Select( x => new DecomposedFilePath( x ) )
// pick files only with the same extensionm as our base file, ignore case
.Where( x => string.Equals( Extenstion, x.Extenstion, StringComparison.OrdinalIgnoreCase) )
// pick files only with the same name (ignoring suffix)
.Where( x => string.Equals( FileNameWithoutExtAndSuffix, x.FileNameWithoutExtAndSuffix, StringComparison.OrdinalIgnoreCase) )
// with the same directory
.Where( x => string.Equals( DirectoryPath, x.DirectoryPath, StringComparison.OrdinalIgnoreCase) )
.ToList(); // create copy for easier debugging
if (decomposed.Count == 0) return this; // no name collision
int? firstFreeSuffix = Enumerable.Range( 1, int.MaxValue) // start numbering duplicates from 1
.Select( x => (int?) x) // change to int? because SuffixAsInt is of that type
.Except( decomposed.Select( x => x.SuffixAsInt) ) // remove existing suffixes
.First(); // get first free suffix
return ReplaceSuffix( firstFreeSuffix );
}
public override string ToString() => FullFilePath;
}
}
This is just a string operation; find the location in the filename string where you want to insert the number, and re-construct a new string with the number inserted. To make it re-usable, you might want to look for a number in that location, and parse it out into an integer, so you can increment it.
Please note that this in general this way of generating a unique filename is insecure; there are obvious race condition hazards.
There might be ready-made solutions for this in the platform, I'm not up to speed with C# so I can't help there.
Take a look at the methods in the Path class, specifically Path.GetFileNameWithoutExtension(), and Path.GetExtension().
You may even find Path.GetRandomFileName() useful!
Edit:
In the past, I've used the technique of attempting to write the file (with my desired name), and then using the above functions to create a new name if an appropriate IOException is thrown, repeating until successful.
This method will add a index to existing file if needed:
If the file exist, find the position of the last underscore. If the content after the underscore is a number, increase this number. otherwise add first index. repeat until unused file name found.
static public string AddIndexToFileNameIfNeeded(string sFileNameWithPath)
{
string sFileNameWithIndex = sFileNameWithPath;
while (File.Exists(sFileNameWithIndex)) // run in while scoop so if after adding an index the the file name the new file name exist, run again until find a unused file name
{ // File exist, need to add index
string sFilePath = Path.GetDirectoryName(sFileNameWithIndex);
string sFileName = Path.GetFileNameWithoutExtension(sFileNameWithIndex);
string sFileExtension = Path.GetExtension(sFileNameWithIndex);
if (sFileName.Contains('_'))
{ // Need to increase the existing index by one or add first index
int iIndexOfUnderscore = sFileName.LastIndexOf('_');
string sContentAfterUnderscore = sFileName.Substring(iIndexOfUnderscore + 1);
// check if content after last underscore is a number, if so increase index by one, if not add the number _01
int iCurrentIndex;
bool bIsContentAfterLastUnderscoreIsNumber = int.TryParse(sContentAfterUnderscore, out iCurrentIndex);
if (bIsContentAfterLastUnderscoreIsNumber)
{
iCurrentIndex++;
string sContentBeforUnderscore = sFileName.Substring(0, iIndexOfUnderscore);
sFileName = sContentBeforUnderscore + "_" + iCurrentIndex.ToString("000");
sFileNameWithIndex = sFilePath + "\\" + sFileName + sFileExtension;
}
else
{
sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
}
}
else
{ // No underscore in file name. Simple add first index
sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
}
}
return sFileNameWithIndex;
}
I did it like this:
for (int i = 0; i <= 500; i++) //I suppose the number of files will not pass 500
{ //Checks if C:\log\log+TheNumberOfTheFile+.txt exists...
if (System.IO.File.Exists(#"C:\log\log"+conta_logs+".txt"))
{
conta_logs++;//If exists, then increment the counter
}
else
{ //If not, then the file is created
var file = System.IO.File.Create(#"C:\log\log" + conta_logs + ".txt");
break; //When the file is created we LEAVE the *for* loop
}
}
I think this version is not so hard like the others, and It's a straightforward answer for what the user wanted.
If you need just a unique file name, so, how about this?
Path.GetRandomFileName()
I ran into this problem and, since none of the other answers seemed to have solved it in the way I wanted to, I did it on my own.
static string CheckIfFileExists(string filePath)
{
if (File.Exists(filePath))
{
string parentDir = Directory.GetParent(filePath).FullName;
string fileName = new DirectoryInfo(filePath).Name;
string extension = Path.GetExtension(fileName);
fileName = Path.GetFileNameWithoutExtension(fileName);
if (CheckIfFileNameHasIndex(fileName))
{
string strIndex = fileName[(fileName.LastIndexOf('(')+1)..fileName.LastIndexOf(')')]; //range
int index = int.Parse(strIndex);
index++;
fileName = fileName.Substring(0, fileName.LastIndexOf('(')) + "(" + index + ')';
filePath = Path.Combine(parentDir, fileName + extension);
return CheckIfFileExists(filePath);
}
else
{
fileName = fileName + " (1)";
filePath = Path.Combine(parentDir, fileName + extension);
return CheckIfFileExists(filePath);
}
}
return filePath;
}
//checks if filename has an index (e.g. "file(2).jpg")
static bool CheckIfFileNameHasIndex(string fileName)
{
bool isSuccessful = false;
if (fileName.LastIndexOf('(')!=-1 && fileName.LastIndexOf(')')!=-1)
{
string index = fileName[(fileName.LastIndexOf('(')+1)..fileName.LastIndexOf(')')]; //range
int result;
isSuccessful = int.TryParse(index, out result);
}
return isSuccessful;
}
The method CheckIfFileExists is recursive, so in theory it should be able to handle a potentially unlimited number of duplicates (e.g. "file (3484939).txt"). Of course, in reality, what happens is that the maximum imposed filename length of your operating system and stuff like eventually become a bottleneck.
I have written a method that returns "next" file name with number.
Supports numbering from 1 to 99.
Examples:
C:\Recovery.txt → C:\Recovery1.txt
C:\Recovery1.txt → C:\Recovery2.txt
How to call:
while (File.Exists( path ))
path = NextFileNum( path );
internal static string NextFileNum( string path )
{
string filename = Path.GetFileNameWithoutExtension( path );
string ext = Path.GetExtension( path );
string dir = Path.GetDirectoryName( path );
for (int i = 99; i > 0; i--)
{
if (filename.EndsWith( i.ToString() ))
{
string suffix = ( i + 1 ).ToString();
filename = filename.Substring( 0, filename.Length - suffix.Length ) + suffix;
return Path.Combine( dir, filename + ext );
}
}
filename = filename + "1";
return Path.Combine( dir, filename + ext );
}
public static string MakeUniqueFilePath(string filePath)
{
if (!File.Exists(filePath)) return filePath;
var directory = Path.GetDirectoryName(filePath);
var fileName = Path.GetFileNameWithoutExtension(filePath);
var fileExt = Path.GetExtension(filePath);
var i = 1;
do
{
filePath = Path.Combine(directory, fileName + "(" + i + ")" + fileExt);
i++;
} while (File.Exists(filePath));
return filePath;
}
Returns files like so:
test.txt
test(1).txt
test(2).txt
etc.
Notes:
Can handle filenames without extensions
Can Handle directories included in the file path.
Does not handle file creation race conditions when saving.
I am using CSV Helper library to produce CSV files for the user to
to populate and upload into the system. My issue is that the WriteHeader method just writes the attributes of a class with names like "PropertyValue", which is not user friendly. Is there a method I can use to make the text produced user friendly but is still able to successfully map the class to the files data?
My code looks like the following:
public ActionResult UploadPropertyCSV(HttpPostedFileBase file)
{
List<PropertyModel> properties = new List<PropertyModel>();
RIMEDb dbContext = new RIMEDb();
bool success = false;
foreach (string requestFiles in Request.Files)
{
if (file != null && file.ContentLength > 0 && file.FileName.EndsWith(".csv"))
{
using(StreamReader str = new StreamReader(file.InputStream))
{
using(CsvHelper.CsvReader theReader = new CsvHelper.CsvReader(str))
{
while (theReader.Read())
{
RIMUtil.PropertyUploadCSVRowHelper row = new RIMUtil.PropertyUploadCSVRowHelper()
{
UnitNumber = theReader.GetField(0),
StreetNumber = theReader.GetField(1),
StreetName = theReader.GetField(2),
AlternateAddress = theReader.GetField(3),
City = theReader.GetField(4)
};
Property property = new Property();
property.UnitNumber = row.UnitNumber;
property.StreetNumber = row.StreetNumber;
property.StreetName = row.StreetName;
property.AlternateAddress = row.AlternateAddress;
property.City = dbContext.PostalCodes.Where(p => p.PostalCode1 == row.PostalCode).FirstOrDefault().City;
dbContext.Properties.Add(property);
try
{
dbContext.SaveChanges();
success = true;
}
catch(System.Data.Entity.Validation.DbEntityValidationException ex)
{
success = false;
RIMUtil.LogError("Ptoblem validating fields in database. Please check your CSV file for errors.");
}
catch(Exception e)
{
RIMUtil.LogError("Error saving property to database. Please check your CSV file for errors.");
}
}
}
}
}
}
return Json(success);
}
I'm wondering if theres some metadata tag or something I can put on top of each attribute in my PropertyUploadCSVRowHelper class to put the text I want produced in the file
Thanks in advance
Not sure if this existed 2 years ago but now, we can change the property/column name by using the following attribute function:
[CsvHelper.Configuration.Attributes.Name("Column/Field Name")]
Full code:
using CsvHelper;
using System.Collections.Generic;
using System.IO;
namespace Test
{
class Program
{
class CsvColumns
{
private string column_01;
[CsvHelper.Configuration.Attributes.Name("Column 01")] // changes header/column name Column_01 to Column 01
public string Column_01 { get => column_01; set => column_01 = value; }
}
static void Main(string[] args)
{
List<CsvColumns> csvOutput = new List<CsvColumns>();
CsvColumns rows = new CsvColumns();
rows.Column_01 = "data1";
csvOutput.Add(rows);
string filename = "test.csv";
using (StreamWriter writer = File.CreateText(filename))
{
CsvWriter csv = new CsvWriter(writer);
csv.WriteRecords(csvOutput);
}
}
}
}
This might not be answering your question directly as you said you wanted to use csvhelper, but if you're only writing small size files (this is a simple function that I use to generate csv. Note, csvhelper will be much better for larger files as this is just building a string and not streaming the data.
Just customise the columns array in the code below variable to suit your needs.
public string GetCsv(string[] columns, List<object[]> data)
{
StringBuilder CsvData = new StringBuilder();
//add column headers
string[] s = new string[columns.Length];
for (Int32 j = 0; j < columns.Length; j++)
{
s[j] = columns[j];
if (s[j].Contains("\"")) //replace " with ""
s[j].Replace("\"", "\"\"");
if (s[j].Contains("\"") || s[j].Contains(" ")) //add "'s around any string with space or "
s[j] = "\"" + s[j] + "\"";
}
CsvData.AppendLine(string.Join(",", s));
//add rows
foreach (var row in data)
{
for (int j = 0; j < columns.Length; j++)
{
s[j] = row[j] == null ? "" : row[j].ToString();
if (s[j].Contains("\"")) //replace " with ""
s[j].Replace("\"", "\"\"");
if (s[j].Contains("\"") || s[j].Contains(" ")) //add "'s around any string with space or "
s[j] = "\"" + s[j] + "\"";
}
CsvData.AppendLine(string.Join(",", s));
}
return CsvData.ToString();
}
Here is a fiddle example of how to use it: https://dotnetfiddle.net/2WHf6o
Good luck.
I would like to create a method which takes either a filename as a string or a FileInfo and adds an incremented number to the filename if the file exists. But can't quite wrap my head around how to do this in a good way.
For example, if I have this FileInfo
var file = new FileInfo(#"C:\file.ext");
I would like the method to give me a new FileInfo with C:\file 1.ext if C:\file.ext
existed, and C:\file 2.ext if C:\file 1.ext existed and so on. Something like this:
public FileInfo MakeUnique(FileInfo fileInfo)
{
if(fileInfo == null)
throw new ArgumentNullException("fileInfo");
if(!fileInfo.Exists)
return fileInfo;
// Somehow construct new filename from the one we have, test it,
// then do it again if necessary.
}
public FileInfo MakeUnique(string path)
{
string dir = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string fileExt = Path.GetExtension(path);
for (int i = 1; ;++i) {
if (!File.Exists(path))
return new FileInfo(path);
path = Path.Combine(dir, fileName + " " + i + fileExt);
}
}
Obviously, this is vulnerable to race conditions as noted in other answers.
Lots of good advice here. I ended up using a method written by Marc in an answer to a different question. Reformatted it a tiny bit and added another method to make it a bit easier to use "from the outside". Here is the result:
private static string numberPattern = " ({0})";
public static string NextAvailableFilename(string path)
{
// Short-cut if already available
if (!File.Exists(path))
return path;
// If path has extension then insert the number pattern just before the extension and return next filename
if (Path.HasExtension(path))
return GetNextFilename(path.Insert(path.LastIndexOf(Path.GetExtension(path)), numberPattern));
// Otherwise just append the pattern to the path and return next filename
return GetNextFilename(path + numberPattern);
}
private static string GetNextFilename(string pattern)
{
string tmp = string.Format(pattern, 1);
if (tmp == pattern)
throw new ArgumentException("The pattern must include an index place-holder", "pattern");
if (!File.Exists(tmp))
return tmp; // short-circuit if no matches
int min = 1, max = 2; // min is inclusive, max is exclusive/untested
while (File.Exists(string.Format(pattern, max)))
{
min = max;
max *= 2;
}
while (max != min + 1)
{
int pivot = (max + min) / 2;
if (File.Exists(string.Format(pattern, pivot)))
min = pivot;
else
max = pivot;
}
return string.Format(pattern, max);
}
Only partially tested it so far, but will update if I find any bugs with it. (Marcs code works nicely!) If you find any problems with it, please comment or edit or something :)
Not pretty, but I've had this for a while :
private string getNextFileName(string fileName)
{
string extension = Path.GetExtension(fileName);
int i = 0;
while (File.Exists(fileName))
{
if (i == 0)
fileName = fileName.Replace(extension, "(" + ++i + ")" + extension);
else
fileName = fileName.Replace("(" + i + ")" + extension, "(" + ++i + ")" + extension);
}
return fileName;
}
Assuming the files already exist:
File.txt
File(1).txt
File(2).txt
the call getNextFileName("File.txt") will return "File(3).txt".
Not the most efficient because it doesn't use binary search, but should be ok for small file count. And it doesn't take race condition into account...
If checking if the file exists is too hard you can always just add a date and time to the file name to make it unique:
FileName.YYYYMMDD.HHMMSS
Maybe even add milliseconds if necessary.
If the format doesn't bother you then you can call:
try{
string tempFile=System.IO.Path.GetTempFileName();
string file=System.IO.Path.GetFileName(tempFile);
//use file
System.IO.File.Delete(tempFile);
}catch(IOException ioe){
//handle
}catch(FileIOPermission fp){
//handle
}
PS:- Please read more about this at msdn before using.
/// <summary>
/// Create a unique filename for the given filename
/// </summary>
/// <param name="filename">A full filename, e.g., C:\temp\myfile.tmp</param>
/// <returns>A filename like C:\temp\myfile633822247336197902.tmp</returns>
public string GetUniqueFilename(string filename)
{
string basename = Path.Combine(Path.GetDirectoryName(filename),
Path.GetFileNameWithoutExtension(filename));
string uniquefilename = string.Format("{0}{1}{2}",
basename,
DateTime.Now.Ticks,
Path.GetExtension(filename));
// Thread.Sleep(1); // To really prevent collisions, but usually not needed
return uniquefilename;
}
As DateTime.Ticks has a resolution of 100 nanoseconds, collisions are extremely unlikely. However, a Thread.Sleep(1) will ensure that, but I doubt that it's needed
Insert a new GUID into the file name.
I must throw my 2-cents in. This is how I did it and it works for my use.
private static string IterateFileName(string fileName)
{
if (!File.Exists(fileName)) return fileName;
FileInfo fi = new FileInfo(fileName);
string ext = fi.Extension;
string name = fi.FullName.Substring(0, fi.FullName.Length - ext.Length);
int i = 2;
while (File.Exists($"{name}_{i}{ext}"))
{
i++;
}
return $"{name}_{i}{ext}";
}
The idea is to get a list of the existing files, parse out the numbers, then make the next highest one.
Note: This is vulnerable to race conditions, so if you have more than one thread creating these files, be careful.
Note 2: This is untested.
public static FileInfo GetNextUniqueFile(string path)
{
//if the given file doesn't exist, we're done
if(!File.Exists(path))
return new FileInfo(path);
//split the path into parts
string dirName = Path.GetDirectoryName(path);
string fileName = Path.GetFileNameWithoutExtension(path);
string fileExt = Path.GetExtension(path);
//get the directory
DirectoryInfo dir = new DirectoryInfo(dir);
//get the list of existing files for this name and extension
var existingFiles = dir.GetFiles(Path.ChangeExtension(fileName + " *", fileExt);
//get the number strings from the existing files
var NumberStrings = from file in existingFiles
select Path.GetFileNameWithoutExtension(file.Name)
.Remove(0, fileName.Length /*we remove the space too*/);
//find the highest existing number
int highestNumber = 0;
foreach(var numberString in NumberStrings)
{
int tempNum;
if(Int32.TryParse(numberString, out tempnum) && tempNum > highestNumber)
highestNumber = tempNum;
}
//make the new FileInfo object
string newFileName = fileName + " " + (highestNumber + 1).ToString();
newFileName = Path.ChangeExtension(fileName, fileExt);
return new FileInfo(Path.Combine(dirName, newFileName));
}
Instead of poking the disk a number of times to find out if it has a particular variant of the desired file name, you could ask for the list of files that already exist and find the first gap according to your algorithm.
public static class FileInfoExtensions
{
public static FileInfo MakeUnique(this FileInfo fileInfo)
{
if (fileInfo == null)
{
throw new ArgumentNullException("fileInfo");
}
string newfileName = new FileUtilities().GetNextFileName(fileInfo.FullName);
return new FileInfo(newfileName);
}
}
public class FileUtilities
{
public string GetNextFileName(string fullFileName)
{
if (fullFileName == null)
{
throw new ArgumentNullException("fullFileName");
}
if (!File.Exists(fullFileName))
{
return fullFileName;
}
string baseFileName = Path.GetFileNameWithoutExtension(fullFileName);
string ext = Path.GetExtension(fullFileName);
string filePath = Path.GetDirectoryName(fullFileName);
var numbersUsed = Directory.GetFiles(filePath, baseFileName + "*" + ext)
.Select(x => Path.GetFileNameWithoutExtension(x).Substring(baseFileName.Length))
.Select(x =>
{
int result;
return Int32.TryParse(x, out result) ? result : 0;
})
.Distinct()
.OrderBy(x => x)
.ToList();
var firstGap = numbersUsed
.Select((x, i) => new { Index = i, Item = x })
.FirstOrDefault(x => x.Index != x.Item);
int numberToUse = firstGap != null ? firstGap.Item : numbersUsed.Count;
return Path.Combine(filePath, baseFileName) + numberToUse + ext;
}
}
Here's one that decouples the numbered naming question from the check of the filesystem:
/// <summary>
/// Finds the next unused unique (numbered) filename.
/// </summary>
/// <param name="fileName">Name of the file.</param>
/// <param name="inUse">Function that will determine if the name is already in use</param>
/// <returns>The original filename if it wasn't already used, or the filename with " (n)"
/// added to the name if the original filename is already in use.</returns>
private static string NextUniqueFilename(string fileName, Func<string, bool> inUse)
{
if (!inUse(fileName))
{
// this filename has not been seen before, return it unmodified
return fileName;
}
// this filename is already in use, add " (n)" to the end
var name = Path.GetFileNameWithoutExtension(fileName);
var extension = Path.GetExtension(fileName);
if (name == null)
{
throw new Exception("File name without extension returned null.");
}
const int max = 9999;
for (var i = 1; i < max; i++)
{
var nextUniqueFilename = string.Format("{0} ({1}){2}", name, i, extension);
if (!inUse(nextUniqueFilename))
{
return nextUniqueFilename;
}
}
throw new Exception(string.Format("Too many files by this name. Limit: {0}", max));
}
And here's how you might call it if you are using the filesystem
var safeName = NextUniqueFilename(filename, f => File.Exists(Path.Combine(folder, f)));
private async Task<CloudBlockBlob> CreateBlockBlob(CloudBlobContainer container, string blobNameToCreate)
{
var blockBlob = container.GetBlockBlobReference(blobNameToCreate);
var i = 1;
while (await blockBlob.ExistsAsync())
{
var newBlobNameToCreate = CreateRandomFileName(blobNameToCreate,i.ToString());
blockBlob = container.GetBlockBlobReference(newBlobNameToCreate);
i++;
}
return blockBlob;
}
private string CreateRandomFileName(string fileNameWithExtension, string prefix=null)
{
int fileExtPos = fileNameWithExtension.LastIndexOf(".", StringComparison.Ordinal);
if (fileExtPos >= 0)
{
var ext = fileNameWithExtension.Substring(fileExtPos, fileNameWithExtension.Length - fileExtPos);
var fileName = fileNameWithExtension.Substring(0, fileExtPos);
return String.Format("{0}_{1}{2}", fileName, String.IsNullOrWhiteSpace(prefix) ? new Random().Next(int.MinValue, int.MaxValue).ToString():prefix,ext);
}
//This means there is no Extension for the file and its fine attaching random number at the end.
return String.Format("{0}_{1}", fileNameWithExtension, new Random().Next(int.MinValue, int.MaxValue));
}
I use this code to create a consecutive _1,_2,_3 etc.. file name everytime a file exists in the blob storage.
Hope this self iterating function may help. It works fine for me.
public string getUniqueFileName(int i, string filepath, string filename)
{
string path = Path.Combine(filepath, filename);
if (System.IO.File.Exists(path))
{
string name = Path.GetFileNameWithoutExtension(filename);
string ext = Path.GetExtension(filename);
i++;
filename = getUniqueFileName(i, filepath, name + "_" + i + ext);
}
return filename;
}
This is an answer to question in this Link, but they marked it as a duplicate, so I post my answer here.
I created this proof of concept class (may contain bugs).
More explanation in code comments.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
namespace ConsoleApp
{
class Program
{
static void Main( string[] args )
{
var testFilePaths = new List<string>
{
#"c:\test\file.txt",
#"c:\test\file(1).txt",
#"c:\test\file(2).txt",
#"c:\TEST2\file(3).txt",
#"c:\test\file(5).txt",
#"c:\test\file(5)abc.txt",
#"c:\test\file(5).avi"
};
// inspect in debbuger for correct values
var withSuffix = new DecomposedFilePath( "c:\\files\\file(13).txt");
var withoutSuffix = new DecomposedFilePath( "c:\\files\\file(abc).txt");
var withExtraNumber = new DecomposedFilePath( "c:\\files\\file(34)xyz(35).txt"); // "(34)" in the middle should be ignored
DecomposedFilePath changedSuffix = withExtraNumber.ReplaceSuffix( 1999 ); // "file(34)xyz(35).txt" -> "file(34)xyz(1999).txt"
DecomposedFilePath removedSuffix = changedSuffix.ReplaceSuffix( null ); // "file(34)xyz(1999).txt" -> "file(34)xyz.txt"
var testPath = new DecomposedFilePath( "c:\\test\\file.txt");
DecomposedFilePath nextPath1 = testPath.GetFirstFreeFilePath( testFilePaths );
// update our list
testFilePaths.Add( nextPath1.FullFilePath );
DecomposedFilePath nextPath2 = testPath.GetFirstFreeFilePath( testFilePaths );
testFilePaths.Add( nextPath2.FullFilePath );
DecomposedFilePath nextPath3 = testPath.GetFirstFreeFilePath( testFilePaths );
}
}
public sealed class DecomposedFilePath
{
public DecomposedFilePath( string filePath )
{
FullFilePath = Path.GetFullPath( filePath );
}
// "c:\myfiles\file(4).txt"
public string FullFilePath { get; }
// "file" or "file(1)"
public string FileNameWithoutExt => Path.GetFileNameWithoutExtension( FullFilePath );
// "file(13)" -> "file"
public string FileNameWithoutExtAndSuffix => FileNameWithoutExt.Substring( 0, FileNameWithoutExt.Length - Suffix.Length ); // removes suffix
// ".txt"
public string Extenstion => Path.GetExtension( FullFilePath );
// "c:\myfiles"
public string DirectoryPath => Path.GetDirectoryName( FullFilePath );
// "file(23)" -> "23", file -> stirng.Empty
public string Suffix
{
get
{
// we want to extract suffix from file name, e.g. "(34)" from "file(34)"
// I am not good at regex, but I hope it will work correctly
var regex = new Regex( #"\([0-9]+\)$" );
Match match = regex.Match( FileNameWithoutExt );
if (!match.Success) return string.Empty; // suffix not found
return match.Value; // return "(number)"
}
}
// tranlates suffix "(33)" to 33. If suffix is does not exist (string.empty), returns null (int?)
public int? SuffixAsInt
{
get
{
if (Suffix == string.Empty) return null;
string numberOnly = Suffix.Substring( 1, Suffix.Length - 2 ); // remove '(' from beginning and ')' from end
return int.Parse( numberOnly );
}
}
// e.g. input is suffix: 56 then it changes file name from "file(34)" to "file(56)"
public DecomposedFilePath ReplaceSuffix( int? suffix ) // null - removes suffix
{
string strSuffix = suffix is null ? string.Empty : $"({suffix})"; // add ( and )
string path = Path.Combine( DirectoryPath, FileNameWithoutExtAndSuffix + strSuffix + Extenstion ); // build full path
return new DecomposedFilePath( path );
}
public DecomposedFilePath GetFirstFreeFilePath( IEnumerable<string> filesInDir )
{
var decomposed = filesInDir
// convert all paths to our class
.Select( x => new DecomposedFilePath( x ) )
// pick files only with the same extensionm as our base file, ignore case
.Where( x => string.Equals( Extenstion, x.Extenstion, StringComparison.OrdinalIgnoreCase) )
// pick files only with the same name (ignoring suffix)
.Where( x => string.Equals( FileNameWithoutExtAndSuffix, x.FileNameWithoutExtAndSuffix, StringComparison.OrdinalIgnoreCase) )
// with the same directory
.Where( x => string.Equals( DirectoryPath, x.DirectoryPath, StringComparison.OrdinalIgnoreCase) )
.ToList(); // create copy for easier debugging
if (decomposed.Count == 0) return this; // no name collision
int? firstFreeSuffix = Enumerable.Range( 1, int.MaxValue) // start numbering duplicates from 1
.Select( x => (int?) x) // change to int? because SuffixAsInt is of that type
.Except( decomposed.Select( x => x.SuffixAsInt) ) // remove existing suffixes
.First(); // get first free suffix
return ReplaceSuffix( firstFreeSuffix );
}
public override string ToString() => FullFilePath;
}
}
This is just a string operation; find the location in the filename string where you want to insert the number, and re-construct a new string with the number inserted. To make it re-usable, you might want to look for a number in that location, and parse it out into an integer, so you can increment it.
Please note that this in general this way of generating a unique filename is insecure; there are obvious race condition hazards.
There might be ready-made solutions for this in the platform, I'm not up to speed with C# so I can't help there.
Take a look at the methods in the Path class, specifically Path.GetFileNameWithoutExtension(), and Path.GetExtension().
You may even find Path.GetRandomFileName() useful!
Edit:
In the past, I've used the technique of attempting to write the file (with my desired name), and then using the above functions to create a new name if an appropriate IOException is thrown, repeating until successful.
This method will add a index to existing file if needed:
If the file exist, find the position of the last underscore. If the content after the underscore is a number, increase this number. otherwise add first index. repeat until unused file name found.
static public string AddIndexToFileNameIfNeeded(string sFileNameWithPath)
{
string sFileNameWithIndex = sFileNameWithPath;
while (File.Exists(sFileNameWithIndex)) // run in while scoop so if after adding an index the the file name the new file name exist, run again until find a unused file name
{ // File exist, need to add index
string sFilePath = Path.GetDirectoryName(sFileNameWithIndex);
string sFileName = Path.GetFileNameWithoutExtension(sFileNameWithIndex);
string sFileExtension = Path.GetExtension(sFileNameWithIndex);
if (sFileName.Contains('_'))
{ // Need to increase the existing index by one or add first index
int iIndexOfUnderscore = sFileName.LastIndexOf('_');
string sContentAfterUnderscore = sFileName.Substring(iIndexOfUnderscore + 1);
// check if content after last underscore is a number, if so increase index by one, if not add the number _01
int iCurrentIndex;
bool bIsContentAfterLastUnderscoreIsNumber = int.TryParse(sContentAfterUnderscore, out iCurrentIndex);
if (bIsContentAfterLastUnderscoreIsNumber)
{
iCurrentIndex++;
string sContentBeforUnderscore = sFileName.Substring(0, iIndexOfUnderscore);
sFileName = sContentBeforUnderscore + "_" + iCurrentIndex.ToString("000");
sFileNameWithIndex = sFilePath + "\\" + sFileName + sFileExtension;
}
else
{
sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
}
}
else
{ // No underscore in file name. Simple add first index
sFileNameWithIndex = sFilePath + "\\" + sFileName + "_001" + sFileExtension;
}
}
return sFileNameWithIndex;
}
I did it like this:
for (int i = 0; i <= 500; i++) //I suppose the number of files will not pass 500
{ //Checks if C:\log\log+TheNumberOfTheFile+.txt exists...
if (System.IO.File.Exists(#"C:\log\log"+conta_logs+".txt"))
{
conta_logs++;//If exists, then increment the counter
}
else
{ //If not, then the file is created
var file = System.IO.File.Create(#"C:\log\log" + conta_logs + ".txt");
break; //When the file is created we LEAVE the *for* loop
}
}
I think this version is not so hard like the others, and It's a straightforward answer for what the user wanted.
If you need just a unique file name, so, how about this?
Path.GetRandomFileName()
I ran into this problem and, since none of the other answers seemed to have solved it in the way I wanted to, I did it on my own.
static string CheckIfFileExists(string filePath)
{
if (File.Exists(filePath))
{
string parentDir = Directory.GetParent(filePath).FullName;
string fileName = new DirectoryInfo(filePath).Name;
string extension = Path.GetExtension(fileName);
fileName = Path.GetFileNameWithoutExtension(fileName);
if (CheckIfFileNameHasIndex(fileName))
{
string strIndex = fileName[(fileName.LastIndexOf('(')+1)..fileName.LastIndexOf(')')]; //range
int index = int.Parse(strIndex);
index++;
fileName = fileName.Substring(0, fileName.LastIndexOf('(')) + "(" + index + ')';
filePath = Path.Combine(parentDir, fileName + extension);
return CheckIfFileExists(filePath);
}
else
{
fileName = fileName + " (1)";
filePath = Path.Combine(parentDir, fileName + extension);
return CheckIfFileExists(filePath);
}
}
return filePath;
}
//checks if filename has an index (e.g. "file(2).jpg")
static bool CheckIfFileNameHasIndex(string fileName)
{
bool isSuccessful = false;
if (fileName.LastIndexOf('(')!=-1 && fileName.LastIndexOf(')')!=-1)
{
string index = fileName[(fileName.LastIndexOf('(')+1)..fileName.LastIndexOf(')')]; //range
int result;
isSuccessful = int.TryParse(index, out result);
}
return isSuccessful;
}
The method CheckIfFileExists is recursive, so in theory it should be able to handle a potentially unlimited number of duplicates (e.g. "file (3484939).txt"). Of course, in reality, what happens is that the maximum imposed filename length of your operating system and stuff like eventually become a bottleneck.
I have written a method that returns "next" file name with number.
Supports numbering from 1 to 99.
Examples:
C:\Recovery.txt → C:\Recovery1.txt
C:\Recovery1.txt → C:\Recovery2.txt
How to call:
while (File.Exists( path ))
path = NextFileNum( path );
internal static string NextFileNum( string path )
{
string filename = Path.GetFileNameWithoutExtension( path );
string ext = Path.GetExtension( path );
string dir = Path.GetDirectoryName( path );
for (int i = 99; i > 0; i--)
{
if (filename.EndsWith( i.ToString() ))
{
string suffix = ( i + 1 ).ToString();
filename = filename.Substring( 0, filename.Length - suffix.Length ) + suffix;
return Path.Combine( dir, filename + ext );
}
}
filename = filename + "1";
return Path.Combine( dir, filename + ext );
}
public static string MakeUniqueFilePath(string filePath)
{
if (!File.Exists(filePath)) return filePath;
var directory = Path.GetDirectoryName(filePath);
var fileName = Path.GetFileNameWithoutExtension(filePath);
var fileExt = Path.GetExtension(filePath);
var i = 1;
do
{
filePath = Path.Combine(directory, fileName + "(" + i + ")" + fileExt);
i++;
} while (File.Exists(filePath));
return filePath;
}
Returns files like so:
test.txt
test(1).txt
test(2).txt
etc.
Notes:
Can handle filenames without extensions
Can Handle directories included in the file path.
Does not handle file creation race conditions when saving.