warrior
warrior

Reputation: 616

Trouble getting file name from file path

How can i get filename from file path, file can be uploaded from different OSX or windows.
What am trying to achieve and what are challenges are below:

-- I can't use fileinfo or path, since filenames coming from OSX can have illegal characters such as |,>,< and because if the name of the filename in Mac OSX is \\path\ex\file, fileinfo or path gives me "file" as filename instead entire name.

-- right now, if file name has :\ in the path, i can easily extract the file name using filename.Substring(filename.LastIndexOf(@"\") + 1)
-- but my problem is with shared files, because shared files full path pattern in windows can be a file name in OSX.

How can i get the full name?
Any suggestions would be appreciated.

Upvotes: 1

Views: 1547

Answers (3)

warrior
warrior

Reputation: 616

Thanks for all the responses, special thanks to @Dour High Arch . Figured out the solution finally. Using fileInfo class, can be done with Path as well but not yet tested.

try
{
  FileInfo fileInformation = new FileInfo(tempFileName);
  String directory = fileInformation.DirectoryName;
  if (tempFileName.StartsWith(directory))
  {
    filename = fileInformation.Name;
  }
}
catch (Exception arugmentException)
{
   if (!((arugmentException is ArgumentException) || 
     (arugmentException is NotSupportedException))) throw;
}

Upvotes: 0

Dour High Arch
Dour High Arch

Reputation: 21722

As others have pointed out; this cannot work. You cannot create filenames that work across all OSes, or even filenames that work across all filesystems in a single OS. I ran into this problem trying to copy NTFS files to an ISO 9660 drive from Windows.

Do not attempt to “sanitize” filenames; the rules are too unreliable, and conflict across filesystems. Use your OS’s API to construct files, like System.IO.Path.GetTempFileName or System.Windows.Controls.OpenFileDialog. If you are trying to construct filenames programmatically, pass a name you believe will work across all client filesystems, like "MyFile" plus an incrementing sequence number, or a hexadecimal GUID, to the API and be prepared for filesystem exceptions when they don’t work.

If you are copying files across filesystems, it is a good idea to store the original filename to show to users, and to use it as the default for File Save dialogs and the like but, again, don’t write your programs to rely on them.

Upvotes: 1

abelenky
abelenky

Reputation: 64730

I think you want to use the static methods of Path:

Path.GetFileName(string);, and Path.GetDirectoryName(string);

Upvotes: 2

Related Questions