Reputation: 2601
I have a problem with getting a final file name in c#.
For example:
If user types two filenames:
"asd." and "asd.."
or
"asd " and "asd " (two spaces)
then method Path.GetFileName
returns "asd.", "asd..", "asd ", "asd " (two spaces).
After saving it on a hard drive (e.g. using StreamWriter), then there is only one file "asd"
How can I check the final name of the input file? I suppose there is a lot of other examples and I could never do it properly manually.
Edit:
I use it to compare two file names and GetFileName returns: for a.txt - a.txt for A.txt - A.txt
But after save it's the same file. The comparison must ignore case.
Upvotes: 4
Views: 282
Reputation: 6698
If you use a FileStream
to open the file, then you can use the FileStream.Name
property after the stream was opened to get the "final" filename.
A crude example:
SaveFileDialog sDlg = new SaveFileDialog();
if (sDlg.ShowDialog() == DialogResult.OK)
{
// E.g., sDlg.FileName returns "myFile..."
FileStream f = new FileStream(sDlg.FileName, FileMode.Create);
Console.WriteLine(f.Name); // then f.Name will return "myFile"
f.Close();
Console.ReadLine();
}
sDlg.Dispose();
Upvotes: 2
Reputation: 12807
There is interesting internal NormalizePath method in Path class in .Net. If you don't mind reflection, you can use it.
string fileName = "asd..";
MethodInfo normalizePathMathod = typeof(Path).GetMethod("NormalizePath", BindingFlags.Static | BindingFlags.NonPublic, null, new Type[] { typeof(string), typeof(bool) }, null);
string normalizedFilePath = (string)normalizePathMathod.Invoke(null, new object[] { fileName, true });
string normalizedFileName = Path.GetFileName(normalizedFilePath);
Just found better solution, without reflection. Path.GetFullPath calls NormalizePath method. So we can change it to:
string fileName = "asd..";
string normalizedFilePath = Path.GetFullPath(fileName);
string normalizedFileName = Path.GetFileName(normalizedFilePath);
Upvotes: 4
Reputation: 14962
Under Windows 7 i cannot rename a file from test to test. (it reverts to test) so i think the renaming comes from the filesystem that enforces specific rules for files rather than .Net.
Even using interop calls you cannot create a file with trailing dots. I don't really think you can get the corrected filename from inside .Net. [EDIT: In fact Ulugbek's answer shows a very good way to do it]
A solution may be to write a empty file with the name to a temporary directory and check what the resulting filename is before deleting it.
Here is some more information: Strange behavior from .NET regarding file paths
Upvotes: 0