Generate a filename with number inside parenthesis - c#

I'm working with asp.net project where user can upload files to server. I want to save the file with its original name, but if file with the same name already exists How can I generate a filename with a number in the parenthesis like windows does?
Files are uploaded to a particular folder and saved with its client side name itself. So, If a file named myimage.jpg is uploaded and a file with same name already exists in the server, I need to rename it to myimage(1).jpg or if 'myimage.jpg' to 'myimage(n).jpg' exists, I need to rename it to myimage(n+1).jpg.
What will be the best way to search for and generate such file names? My first guess was to use linq with regex over DirectoryInfo.EnumerateFiles(), but is that a good approach?

If the files with same orginal name don't have to be shown sorted by upload date/time, you could simply append System.Guid.NewGuid().ToString() to the file name.

public static object lockObject = new object();
void UploadFile(...)
{
//-- other code
lock (lockObject)
{
int i = 1;
string saveFileAs = "MyFile.txt";
while (File.Exists(saveFileAs))
{
string fileNameWithoutExt = Path.GetFileNameWithoutExtension(saveFileAs);
string ext = Path.GetExtension(saveFileAs)
saveFileAs = String.Concat(fileNameWithoutExt, "(", i.ToString(), ")", ext);
i++;
}
//-- Now you can save the file.
}
}

You don't need LINQ or regex.
If the original filename exists, append (1) to the name.
If that exists, append (2) to the (original) name.
And so on...

Related

How to convert a String in String Array?

I am working on a login system on WPF and C#, and im taking the Input out of a textbox and checking if the input (username or else) exists.
I do that with:
string selectedUser = User.Text;
if (File.Exists(#"" + path + selectedUser + ".txt"))
then i want to create a text file with the name of the user.
i do that with:
File.WriteAllLines(#"" + result + User + ".txt", User);
but it tells me that i cant convert a String to String[] (array).
And i searched the whole internet but couldnt find how to convert it, so i would love to hear a answer
from you guys.
The File.WriteAllLines method writes an array of string to a file.
public static void WriteAllLines (string path, string[] contents);
Creates a new file, writes one or more strings to the file, and then closes the file.
Instead, use the File.WriteAllText method.
public static void WriteAllText (string path, string contents);
Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.

how to verify if an input read from console is a file name or a file full path

I have a console application in C# and I would like to load an xml file, the path to the file is provided via console.readline(). But, I would like to load the file from the provided path but if the user only provides the name of the file I would like to search for it in the local folder from where the application is running. How can I know when I get only a file name as an input or a file full path.
I managed that using: var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
But this ugly and probably very buggy.
Full code:
var xmlFilePath = Console.ReadLine();
var xmlFile = new XmlDocument();
var isFileNameOnly = ((xmlFilePath.IndexOf("\\")) == -1);
try
{
if (isFileNameOnly)
{
xmlFilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, xmlFilePath);
}
xmlFile.Load(xmlFilePath);
}
Thx
You can check if the file name entered by user actually exists using Exists() method. If it returns true load the file.
File.Exists(xmlFilePath)
Also XmlDocument.Load() if provided only file name will try to find the file in the BaseDirectory itself. So if file.Exists() return true you can assume XmlDocument.Load will load it whether it is local or absolute path.
This will return false:
bool isFolder = Path.IsPathRooted(#"Text.txt");
This will return true:
bool isFolder = Path.IsPathRooted(#"C:\Text");
Your approach is the same that I would have chosen. If the param doesn't contain any directory delimiter char, then it must be a filename only. Maybe it would be a little more elegant if you did it like this:
bool isFileNameOnly = !xmlFilePath.Contains(Path.DirectorySeparatorChar.ToString());

How to copy and paste the files from shared folder or from another server?

I am creating application. In that, I put combo box, combo box filled by application no. came from db. on the selection of combo box the grid fill that files which in another machine in drive. Like //user/public/af001/edit/test.JPEG and in grid I put the download link on particular row for download that file in my machine but issue is when I am downloading that file, I am not geting //user/public/af001/edit/test.JPEG.
if (e.Column Index == 0)
{
int row;
//Get the row index
row = e.Row Index;
string old Path = #"~\\Users\Public\AS\AFS1402190001\Edit\test.JPEG";
string new path = #"E:\example\";
string new File Name = "new file name";
File Info f1 = new File Info(old Path);
if (f1.Exists)
{
if (!Directory.Exists(new path))
{
Directory.Create Directory(new path);
}
f1.Copy To(string.Format("{0}{1}{2}", new path, new File Name, f1.Extension));
}
}
Can you tell me what is the issue?
Thanks for help.
The problem is at this line:
string.Format("{0}{1}{2}", new path, new File Name, f1.Extension);
it looks you are not building a correct file patch. try to use System.IO.Path.Combine to combine directory and fileName. something like:
System.IO.Path.Combine(dirPath, string.Format("{0}.{1}", fileName, extension));
of course, you might want to make sure the path/filename does not have invalid chars, you can use System.IO.Path.GetInvalidFileNameChars() and System.IO.Path.GetInvalidPathChars() to get those illegal chars that you need to avoid.

C# mass File renamer

i want to create C# mass file renamer, here is my UI
i have created tes folder, inside of tes there's a file which is 1.txt.
i want to create my program to add prefix and suffix to the files, so 1.txt will become
prefix1suffix
but then i got an error
it's said file already exist though there's only one file on tes folder, which is 1.txt how do i make it work ? where's the error comes from ?
i have tried the following code
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
File.Move(f.FullName,"stackoverflow");
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
and it returns same error as the second picture above.
the following picture is tes folder, there's nothing in tes folder except 1.txt
You are calling File.Move() with a full path for your sourceFileName and a relative path for your destFileName. The relative file path is relative to the current working directory and not to the source file path. I expect that a stackoverflow file exists in the current working directory, most likely created the first time you ran this code.
your File.Move is changing them all to StackOverflow not using the prefix and suffix. If you only have one file in the directory it shouldn't be an issue. Are you sure there is only 1 file?
public static void Move(
string sourceFileName,
string destFileName
)
Looking at this answer might be the clue as you are specifying relative path for the destination file. To obtain the current working directory, see GetCurrentDirectory
The sourceFileName and destFileName arguments are permitted to specify
relative or absolute path information. Relative path information is
interpreted as relative to the current working directory.
You should change
File.Move(f.FullName,"stackoverflow");
to
string fileName = f.Name.Replace(f.Extenstion,string.Empty);
string newFileName = string.Format("{0}{1}{2}",prefix,fileName,suffix);
string newFileWithPath = Path.Combine(f.Directory,newFileName);
if (!File.Exists(newFileWithPath))
{
File.Move(f.FullName,newFileWithPath);
}
The code above will give you that error since, after the first run through, "stackoverflow" exists as a file. Make sure that you check if the destination file exists (using File.Exists) before calling File.Move.
Since your goal is renaming, I would suggest using a test folder filled with files rather than using a piecemeal approach. See if something like this helps:
private void Rename(string prefix, string filepath, string suffix)
{
//i don't use prefix suffix yet to make sure if my function works
DirectoryInfo d = new DirectoryInfo(filepath);
FileInfo[] file = d.GetFiles();
try
{
foreach (FileInfo f in file )
{
f.MoveTo(#filepath + #"\" + prefix + f.Name.Insert(f.Name.LastIndexOf('.'),suffix));
}
}
catch (Exception e)
{
cmd.cetakGagal(e.ToString(), title);
}
cmd.cetakSukses("Rename Success", title);
}
on a side note using a listview to display the filenames and the changes before they're committed will help prevent unwanted changes.

Why does the Name Property of FileInfo object start with "~$"?

So I'm writing some code that is going through a directory of .xlsx files and picking the file that was created last. It's a simple task, but there is something a bit strange happening with the Name property of a particular FileInfo object and potentially there are more cases of this occurring.
Here is my code:
DirectoryInfo di = new DirectoryInfo(FolderPath);
FileInfo[] FileArray = di.GetFiles("*.xlsx", SearchOption.AllDirectories);
if (FileArray.Count() != 0)
{
DateTime latestDate = DateTime.MinValue;
string FileName = String.Empty;
foreach (FileInfo File in FileArray)
{
if (File.CreationTime > latestDate)
{
latestDate = File.CreationTime;
FileName = File.FullName;
}
}
}
The FileName is important because I use it to query the latest file for information and display it. However, the Name property of a particular .xlsx file (potentially more) is appearing like this ~$File.xlsx when in fact the file name is really File.xlsx. This causes the FullName property to contain these characters as well.
Is there any way to fix this? What triggers this?
Opening an xlsx file results in Excel creating a hidden file with the same name preceded by "~$". So if one of these Excel files are open at the time you retrieve the content of the directory, you will also get the temp file.
Add a filter that excludes hidden files and your issue is fixed.
Example:
FileAttributes attributes = File.GetAttributes(path);
if((attributes & FileAttributes.Hidden) == FileAttributes.Hidden)
{
// Hidden file, just skip it
}
From http://msdn.microsoft.com/en-us/library/system.io.file.getattributes.aspx
~$ indicates that the file is a temporary file used by Microsoft Office. See here for additional information.

Categories

Resources