How to get the final file name

I have a problem getting the final file name in C #.

For instance:

If the user enters two file names:

"ASD". and "asd .."

or

"asd" and "asd" (two spaces)

then the method Path.GetFileNamereturns "asd.", "asd ..", "asd", "asd" (two spaces).

After saving to the hard disk (for example, using StreamWriter), there is only one "asd" file

How to check the final input file name? I believe there are many other examples, and I could never have done it correctly manually.

Edit

I use it to compare two file names and returns GetFileName: for a.txt - a.txt for A.txt - A.txt

But after saving, save the same file. The comparison should ignore the case.

+4
3

NormalizePath Path .Net. , .

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);

, . Path.GetFullPath NormalizePath. :

string fileName = "asd..";
string normalizedFilePath = Path.GetFullPath(fileName);
string normalizedFileName = Path.GetFileName(normalizedFilePath);
+4

FileStream, FileStream.Name , , "" .

:

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();
+2

Windows 7 . ( ), , , , .Net.

Even using interop calls, you cannot create a file with trailing dots. I really don't think you can get the corrected file name from inside .Net. [EDIT: Actually, Ulugbek’s answer shows a very good way to do this]

The solution may be to write an empty file with the name to a temporary directory and check which resulting file name before deleting.

Here's some more info: Strange .NET behavior regarding file paths

0
source

Source: https://habr.com/ru/post/1531513/


All Articles