I have the following function:
public static string GetRelativePath(string fromPath, string toPath)
{
// we also tried the Uri solution but that does not return .. when you need to traverse
// one up only
// uri1 = "bla\foo"
// uri2 = "bla\bar"
// uri1.MakeRelaitveto(uri2) != "..\bar"
var path = new StringBuilder(260); // MAX_PATH
if (PathRelativePathTo(
path,
fromPath.Replace('/', '\\'),
FILE_ATTRIBUTE_DIRECTORY,
toPath.Replace('/', '\\'),
FILE_ATTRIBUTE_DIRECTORY) == 0)
{
return toPath;
}
return path.ToString().Replace('\\', Path.DirectorySeparatorChar);
}
[DllImport("shlwapi.dll", SetLastError = true)]
private static extern int PathRelativePathTo(
StringBuilder pszPath, string pszFrom, int dwAttrFrom, string pszTo, int dwAttrTo);
}
Which I call with the following testcase:
GetPathRelativeTo("C:\\somεpath", "C:\\anothεrpath").Shouldbe("..\\anothεrpath")
but instead it is returning ..\\anotherpath. Notice that the ε has been replaced by an e.
I tried using PathRelativePathToW but that works even less (other test cases fail).
Does anybody know what is going on and how I can prevent the replacement of the char?
This seems to be a problem with shlwapi under the hood, not anything on the C# side.
Consider using System.Uri instead.
How do I get a relative path from one path to another in C#
Related
I'm trying to import dll coded in C++ in C#. What's really stange and bothers me is that: different parameter count or type in C#, and I get different result. Let me explain in detail.
Test Code in C++:
FUN_API BOOL WriteUPS()
{
//The maximum size of an output report.
const unsigned short int MAXREPORTSIZE = 65;
BOOL bWriteSuccess = FALSE;
DWORD BytesWritten = 0;
CHAR OutputReport[MAXREPORTSIZE];
ULONG Result;
CString strBytesWritten = "";
memset(OutputReport,'\0',MAXREPORTSIZE);
//The first byte is the report number.
OutputReport[0]=0;
//memcpy(OutputReport+1,Command,MAXREPORTSIZE-1);
OutputReport[1]=0x41;
OutputReport[2]=0x51;
Result = WriteFile
(ReadHandle,
OutputReport,
Capabilities.OutputReportByteLength,
&BytesWritten,
(LPOVERLAPPED) &HIDOverlapped);
Result = WaitForSingleObject
(hEventObject,
500);
switch (Result)
{
case WAIT_OBJECT_0:
{
bWriteSuccess = TRUE;
break;
}
case WAIT_TIMEOUT:
{
//Cancel the Write operation.
Result = CancelIo(ReadHandle);
bWriteSuccess = FALSE;
break;
}
default:
{
bWriteSuccess = FALSE;
break;
}
}
ResetEvent(hEventObject);
if(!bWriteSuccess)
return FALSE;
else
return TRUE;
}
Calling function in C#:
private const string DLLPath = #"C:/Test/USBTest/USBComm.dll";
[DllImport(DLLPath,CharSet=CharSet.Ansi, CallingConvention = CallingConvention.Cdecl)]
public static extern bool WriteUPS();
It works well and I can see good data transfer ("AQ") from PC to USB device.
However, if I modify like following while the other part remains:
//Modification in C++
FUN_API BOOL WriteUPS(char Command[])
//Modification in C#
public static extern bool WriteUPS(char[] command);
Then I got error data (not "AQ").
Again, if I modify like following while the other part remains:
//Modification in C++
FUN_API BOOL WriteUPS(char* Command)
//Modification in C#
public static extern bool WriteUPS(string command);
Then I got some different error data (not "AQ").
Could anyone please help to explain ?
Use this:
//Modification in C++
FUN_API BOOL WriteUPS(char* Command)
//Modification in C#
public static extern bool WriteUPS(string command);
in this way the string is \0 terminated automatically. If you use
FUN_API BOOL WriteUPS(char Command[])
then you'll have to make sure the last character of the string is \0
Then
memcpy(OutputReport+1,Command,strlen(Command));
You were copying too many bytes. The right number of bytes to copy is strlen(Command)
I advise that you can pass two parameters to this method. One is the data and second is length. This way you will know exactly how many characters to copy from the parameter.
Other than that are you sure your command length will not be more than 65? You should probably not fix it so that any data size can be sent
Put a '\0' at end of length passed. It will work both for char array and pointer versions.
I have a list view and there are multiple columns with long text values, like a column with destination file path it has a value like c:\users\kavya\new\coding\img1000.jpg
something very big.
I want to adjust the text according to size of the column when the users uses the scroll bar:
with width something very big all the data c:\users\kavya\new\coding\img1000.jpg
should be visible and when he scrolls the column header to very small only the c:\img1000.jpg has to be viewed but the memory should have the entire path
actualy we see something like c:\users\kavya…...
How can I do this?
By doing Windows API call PathCompactPathEx,
[DllImport("shlwapi.dll", CharSet = CharSet.Auto)]
static extern bool PathCompactPathEx([Out] StringBuilder pszOut, string szPath, int cchMax, int dwFlags);
static string PathShortener(string path, int length)
{
StringBuilder sb = new StringBuilder();
PathCompactPathEx(sb, path, length, 0);
return sb.ToString();
}
OR You can try like this :
string PathShortener(string path)
{
const string pattern = #"^(\w+:|\\)(\\[^\\]+\\[^\\]+\\).*(\\[^\\]+\\[^\\]+)$";
const string replacement = "$1$2...$3";
if (Regex.IsMatch(path, pattern))
{
return Regex.Replace(path, pattern, replacement);
}
else
{
return path;
}
}
OR You can use like below :
string ellipsisedPath = OriginalPath + '\0';
visit: Add Ellipsis to a Path in a WinForms Program without Win32 API call (revisited)
I am using a FileSystemWatcher to monitor a folder. But when there is some event happening in the directory, I don't know how to search who made a impact on that file. I tried to use EventLog. It just couldn't work. Is there another way to do it?
I cant remember where I found this code but its an alternative to using pInvoke which I think is a bit overkill for this task. Use the FileSystemWatcher to watch the folder and when an event fires you can work out which user made the file change using this code:
private string GetSpecificFileProperties(string file, params int[] indexes)
{
string fileName = Path.GetFileName(file);
string folderName = Path.GetDirectoryName(file);
Shell32.Shell shell = new Shell32.Shell();
Shell32.Folder objFolder;
objFolder = shell.NameSpace(folderName);
StringBuilder sb = new StringBuilder();
foreach (Shell32.FolderItem2 item in objFolder.Items())
{
if (fileName == item.Name)
{
for (int i = 0; i < indexes.Length; i++)
{
sb.Append(objFolder.GetDetailsOf(item, indexes[i]) + ",");
}
break;
}
}
string result = sb.ToString().Trim();
//Protection for no results causing an exception on the `SubString` method
if (result.Length == 0)
{
return string.Empty;
}
return result.Substring(0, result.Length - 1);
}
Shell32 is a reference to the DLL: Microsoft Shell Controls And Automation - its a COM reference
Here is some example's of how you call the method:
string Type = GetSpecificFileProperties(filePath, 2);
string ObjectKind = GetSpecificFileProperties(filePath, 11);
DateTime CreatedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 4));
DateTime LastModifiedDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 3));
DateTime LastAccessDate = Convert.ToDateTime(GetSpecificFileProperties(filePath, 5));
string LastUser = GetSpecificFileProperties(filePath, 10);
string ComputerName = GetSpecificFileProperties(filePath, 53);
string FileSize = GetSpecificFileProperties(filePath, 1);
Or get multiple comma separated properties together:
string SizeTypeAndLastModDate = GetSpecificFileProperties(filePath, new int[] {1, 2, 3});
Note: This solution has been tested on Windows 7 and Windows 10. It wont work unless running in a STA as per Exception when using Shell32 to get File extended properties and you will see the following error:
Unable to cast COM object of type 'Shell32.ShellClass' to interface type 'Shell32.IShellDispatch6'
You need to enable auditing on the file system (and auditing is only available on NTFS). You do this by applying a group policy or local security policy. You will also have to enable auditing on the file you want to monitor. You do it the same way as you modify the permissions on the file.
Auditing events are then written to the security event log. You will have to monitor this event log for the auditing events you are interested in. One way to do this is to create a scheduled task that starts an application when the events you are interested in are logged. Starting a new process for each event is only viable if events aren't logged at a very high rate though. Otherwise you will likely experience performance problems.
Basically, you don't want to look at the contents or attributes of the file (which the shell function GetFileDetails does). Also, you don't want to use a file sharing API to get the network user that has the file open (which NetGetFileInfo does). You want to know the user of the process that last modified the file. This information is not normally recorded by Windows because it would require too many resources to do that for all file activities. Instead you can selectively enable auditing for specific users doing specifc actions on specific files (and folders).
It seems that you'll need to invoke Windows API functions to get what you want, which involves PInvoke. Some people on another forum have been looking into it and figured something out, you can find their solution here. However, it seems to work only with files on network shares (not on your local machine).
For future reference, this is the code posted by dave4dl:
[DllImport("Netapi32.dll", SetLastError = true)]
static extern int NetApiBufferFree(IntPtr Buffer);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
struct FILE_INFO_3
{
public int fi3_id;
public int fi3_permission;
public int fi3_num_locks;
public string fi3_pathname;
public string fi3_username;
}
[DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int NetFileEnum(
string servername,
string basepath,
string username,
int level,
ref IntPtr bufptr,
int prefmaxlen,
out int entriesread,
out int totalentries,
IntPtr resume_handle
);
[DllImport("netapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern int NetFileGetInfo(
string servername,
int fileid,
int level,
ref IntPtr bufptr
);
private int GetFileIdFromPath(string filePath)
{
const int MAX_PREFERRED_LENGTH = -1;
int dwReadEntries;
int dwTotalEntries;
IntPtr pBuffer = IntPtr.Zero;
FILE_INFO_3 pCurrent = new FILE_INFO_3();
int dwStatus = NetFileEnum(null, filePath, null, 3, ref pBuffer, MAX_PREFERRED_LENGTH, out dwReadEntries, out dwTotalEntries, IntPtr.Zero);
if (dwStatus == 0)
{
for (int dwIndex = 0; dwIndex < dwReadEntries; dwIndex++)
{
IntPtr iPtr = new IntPtr(pBuffer.ToInt32() + (dwIndex * Marshal.SizeOf(pCurrent)));
pCurrent = (FILE_INFO_3)Marshal.PtrToStructure(iPtr, typeof(FILE_INFO_3));
int fileId = pCurrent.fi3_id;
//because of the path filter in the NetFileEnum function call, the first (and hopefully only) entry should be the correct one
NetApiBufferFree(pBuffer);
return fileId;
}
}
NetApiBufferFree(pBuffer);
return -1; //should probably do something else here like throw an error
}
private string GetUsernameHandlingFile(int fileId)
{
string defaultValue = "[Unknown User]";
if (fileId == -1)
{
return defaultValue;
}
IntPtr pBuffer_Info = IntPtr.Zero;
int dwStatus_Info = NetFileGetInfo(null, fileId, 3, ref pBuffer_Info);
if (dwStatus_Info == 0)
{
IntPtr iPtr_Info = new IntPtr(pBuffer_Info.ToInt32());
FILE_INFO_3 pCurrent_Info = (FILE_INFO_3)Marshal.PtrToStructure(iPtr_Info, typeof(FILE_INFO_3));
NetApiBufferFree(pBuffer_Info);
return pCurrent_Info.fi3_username;
}
NetApiBufferFree(pBuffer_Info);
return defaultValue; //default if not successfull above
}
private string GetUsernameHandlingFile(string filePath)
{
int fileId = GetFileIdFromPath(filePath);
return GetUsernameHandlingFile(fileId);
}
This has been discussed many times. My answer from the same question:
You can't do this asynchronously with FileSystemWatcher, however you can do this synchronously using file system filter driver. The driver lets you get the user name of the account performing the operation.
Use code posted by dave4dl and update declare struct FILE_INFO_3 as following,
you can monitor user name of create and update file action(It is like to combination of FileSystemWatcher and OpenFiles.exe's functions of FileSharing Server)
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
public struct FILE_INFO_3
{
public int fi3_id;
public int fi3_permission;
public int fi3_num_locks;
[MarshalAs(UnmanagedType.LPWStr)]
public string fi3_pathname;
[MarshalAs(UnmanagedType.LPWStr)]
public string fi3_username;
}
So here is the deal, Im working a C# application that calls into a legacy C++ dll, which in turns loops through a directory pulling back the names of certain directories, i.e directories that have .lib, I have a directory with the following 3 folders: Default.Lib,中文文本帧的文件.lib,我们的.lib.
As you can see we have some chinese folder names, a string is built in memory by the c++ code as you can see below, it use strcat to build it in memory. however when control is returned back to the c# code, it appears part of that data is lost and the only two folders left are the first two. Default.Lib,中文文本帧的文件.lib, something with 我们的.lib gets lost in translation, I would greatly appreciate any insights anyone may have. thanks.
C# code snippet
lock (padLock)
{
ConnectSign(service);
int size = MaxFileListSize * 100;
byte[] mem = new byte[size];
string finalList;
int used = size;
int fileCount = 0;
string library = "*";
string extension = "*";
V7_FILE_LIST_TYPE type = V7_FILE_LIST_TYPE.LibraryList;
fixed (byte* listbytes = mem)
{
int error = NativeMethods.GetFileDirInfo(sign, type, fileServer, library, extension, &fileCount, listbytes, &used);
if (error != 0)
throw new V7ResponseException(error, sign, service, "GetFileDirInfo");
}
finalList = Encoding.Default.GetString(mem, 0, (int)used);
string[] libraryArray = finalList.Split(new char[] { '\n', '\0' }, StringSplitOptions.RemoveEmptyEntries);
for (int i = 0; i < libraryArray.Length; i++)
{
int index = libraryArray[i].LastIndexOf(".lib", StringComparison.OrdinalIgnoreCase);
if (index > 0)
libraryArray[i] = libraryArray[i].Substring(0, index);
//libraryArray[i] = libraryArray[i].Trim().ToLower(CultureInfo.CurrentCulture).Replace(".lib", string.Empty);
}
return libraryArray;
}
[DllImport("V7SSRpc.dll", CharSet = CharSet.Ansi, EntryPoint = "V7ssGetFileDirInfo", BestFitMapping = false, ThrowOnUnmappableChar = true)]
public static extern int GetFileDirInfo(string sign, V7_FILE_LIST_TYPE type, string fileServer, string library, string extension, int* fileCount, byte* files, int* bytesUsed);
*****************************C++ DLL code--------------------------------------
//--------------------------------------------------------------------
// RETURN :
//
// PARAMS : eListType
// szServer
// szLib
// szExt
// *pdwFileCnt
// *pbyFileBuf
// *pdwFileBufSize
//
// REMARKS:
//
BOOL CVSign::apiGetFileDirInfo(V7_FILE_LIST_TYPE eListType, LPCSTR szServer, LPCSTR szLib, LPCSTR szExt,
DWORD *pdwFileCnt, char *pbyFileBuf, DWORD *pdwFileBufSize) const
{
BOOL bReturn=TRUE;
CString sServer(szServer);
CString sLib(szLib);
CString sExt(szExt);
CString sFileInfo, sTemp;
CStringArray asFiles;
CFileStatus status;
CV7Files V7Files;
DWORD dwBufUsed=0;
// SOME OTHER LOGIC (not posted)
USES_CONVERSION;
//CoInitialize(NULL);
//AVIFileInit();
CString sFilePath;
CV7SequenceFile V7Seq;
CV7FileInfo fileInfo;
// go through list of files and build the buffer with file names and other info
for (nFile=0; nFile<nFiles; nFile++)
{
// MORE OBSCURED LOGIC
sFileInfo += _T("\n");
// add file info to buffer
int nLen = sFileInfo.GetLength();
if (dwBufUsed+nLen<*pdwFileBufSize)
{
strcat(pbyFileBuf, T2CA(sFileInfo)); //<--- THIS IS THE IMPORTANT PART
int nTemp = sFileInfo.GetLength();
dwBufUsed += nTemp;
}
else
{
*pdwFileBufSize = 0;
AVIFileExit();
CoUninitialize();
return FALSE;
}
} // end for files
//AVIFileExit();
//CoUninitialize();
*pdwFileBufSize = dwBufUsed;
return bReturn;
} // end apiGetFileDirInfo()
I suspect the problem is that you're specifying Charset=CharSet.Ansi, so the default marshaling behavior is to convert the returned string to ANSI. That's going to cause a problem.
You probably want to specify string Charset=CharSet.Unicode, and possibly specify custom marshaling for some strings. See http://msdn.microsoft.com/en-us/library/s9ts558h.aspx#cpcondefaultmarshalingforstringsanchor5 for information on how to change the string marshaling behavior for individual parameters.
I need to know which is the real path of a given path.
For example:
The real path is: d:\src\File.txt
And the user give me: D:\src\file.txt
I need as a result: d:\src\File.txt
You can use this function:
[DllImport("kernel32.dll", SetLastError=true, CharSet=CharSet.Auto)]
static extern uint GetLongPathName(string ShortPath, StringBuilder sb, int buffer);
[DllImport("kernel32.dll")]
static extern uint GetShortPathName(string longpath, StringBuilder sb, int buffer);
protected static string GetWindowsPhysicalPath(string path)
{
StringBuilder builder = new StringBuilder(255);
// names with long extension can cause the short name to be actually larger than
// the long name.
GetShortPathName(path, builder, builder.Capacity);
path = builder.ToString();
uint result = GetLongPathName(path, builder, builder.Capacity);
if (result > 0 && result < builder.Capacity)
{
//Success retrieved long file name
builder[0] = char.ToLower(builder[0]);
return builder.ToString(0, (int)result);
}
if (result > 0)
{
//Need more capacity in the buffer
//specified in the result variable
builder = new StringBuilder((int)result);
result = GetLongPathName(path, builder, builder.Capacity);
builder[0] = char.ToLower(builder[0]);
return builder.ToString(0, (int)result);
}
return null;
}
As an old-timer, I always used FindFirstFile for this purpose. The .Net translation is:
Directory.GetFiles(Path.GetDirectoryName(userSuppliedName), Path.GetFileName(userSuppliedName)).FirstOrDefault();
This only gets you the correct casing for the filename portion of the path, not then entire path.
JeffreyLWhitledge's comment provides a link to a recursive version that can work (though not always) to resolve the full path.
Alternative Solution
Here is a solution that worked for me to move files between Windows and a server using case sensitive paths. It walks down the directory tree and corrects each entry with GetFileSystemEntries(). If part of the path is invalid (UNC or folder name), then it corrects the path only up to that point and then uses the original path for what it can't find. Anyway, hopefully this will save others time when dealing with the same issue.
private string GetCaseSensitivePath(string path)
{
var root = Path.GetPathRoot(path);
try
{
foreach (var name in path.Substring(root.Length).Split(Path.DirectorySeparatorChar))
root = Directory.GetFileSystemEntries(root, name).First();
}
catch (Exception e)
{
// Log("Path not found: " + path);
root += path.Substring(root.Length);
}
return root;
}
The way to get the actual path of a file (this won't work for folders) is to follow these steps:
Call CreateFileMapping to create a mapping for the file.
Call GetMappedFileName to get the name of the file.
Use QueryDosDevice to convert it to an MS-DOS-style path name.
If you feel like writing a more robust program that also works with directories (but with more pain and a few undocumented features), follow these steps:
Get a handle to the file/folder with CreateFile or NtOpenFile.
Call NtQueryObject to get the full path name.
Call NtQueryInformationFile with FileNameInformation to get the volume-relative path.
Using the two paths above, get the component of the path that represents the volume itself. For example, if you get \Device\HarddiskVolume1\Hello.txt for the first path and \Hello.txt for the second, you now know the volume's path is \Device\HarddiskVolume1.
Use either the poorly-documented Mount Manager I/O Control Codes or QueryDosDevice to convert substitute the volume portion of the full NT-style path with the drive letter.
Now you have the real path of the file.
As Borja's answer does not work for volumes where 8.3 names are disabled, here the recursive implementation that Tergiver suggests (works for files and folders, as well as the files and folders of UNC shares but not on their machine names nor their share names).
Non-existing file or folders are no problem, what exists is verified and corrected, but you might run into folder-redirection issues, e.g when trying to get the correct path of "C:\WinDoWs\sYsteM32\driVErs\eTC\Hosts" you'll get "C:\Windows\System32\drivers\eTC\hosts" on a 64bit windows as there is no "etc" folder withing "C:\Windows\sysWOW64\drivers".
Test Scenario:
Directory.CreateDirectory(#"C:\Temp\SomeFolder");
File.WriteAllLines(#"C:\Temp\SomeFolder\MyTextFile.txt", new String[] { "Line1", "Line2" });
Usage:
FileInfo myInfo = new FileInfo(#"C:\TEMP\SOMEfolder\MyTeXtFiLe.TxT");
String myResult = myInfo.GetFullNameWithCorrectCase(); //Returns "C:\Temp\SomeFolder\MyTextFile.txt"
Code:
public static class FileSystemInfoExt {
public static String GetFullNameWithCorrectCase(this FileSystemInfo fileOrFolder) {
//Check whether null to simulate instance method behavior
if (Object.ReferenceEquals(fileOrFolder, null)) throw new NullReferenceException();
//Initialize common variables
String myResult = GetCorrectCaseOfParentFolder(fileOrFolder.FullName);
return myResult;
}
private static String GetCorrectCaseOfParentFolder(String fileOrFolder) {
String myParentFolder = Path.GetDirectoryName(fileOrFolder);
String myChildName = Path.GetFileName(fileOrFolder);
if (Object.ReferenceEquals(myParentFolder, null)) return fileOrFolder.TrimEnd(new char[]{Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar });
if (Directory.Exists(myParentFolder)) {
//myParentFolder = GetLongPathName.Invoke(myFullName);
String myFileOrFolder = Directory.GetFileSystemEntries(myParentFolder, myChildName).FirstOrDefault();
if (!Object.ReferenceEquals(myFileOrFolder, null)) {
myChildName = Path.GetFileName(myFileOrFolder);
}
}
return GetCorrectCaseOfParentFolder(myParentFolder) + Path.DirectorySeparatorChar + myChildName;
}
}
Here's an alternate solution, works on files and directories. Uses GetFinalPathNameByHandle, which is only supported for desktop apps on Vista/Server2008 or above according to docs.
Note that it will resolve a symlink if you give it one, which is part of finding the "final" path.
// http://www.pinvoke.net/default.aspx/shell32/GetFinalPathNameByHandle.html
[DllImport("Kernel32.dll", SetLastError = true, CharSet = CharSet.Auto)]
static extern uint GetFinalPathNameByHandle(SafeFileHandle hFile, [MarshalAs(UnmanagedType.LPTStr)] StringBuilder lpszFilePath, uint cchFilePath, uint dwFlags);
private const uint FILE_NAME_NORMALIZED = 0x0;
static string GetFinalPathNameByHandle(SafeFileHandle fileHandle)
{
StringBuilder outPath = new StringBuilder(1024);
var size = GetFinalPathNameByHandle(fileHandle, outPath, (uint)outPath.Capacity, FILE_NAME_NORMALIZED);
if (size == 0 || size > outPath.Capacity)
throw new Win32Exception(Marshal.GetLastWin32Error());
// may be prefixed with \\?\, which we don't want
if (outPath[0] == '\\' && outPath[1] == '\\' && outPath[2] == '?' && outPath[3] == '\\')
return outPath.ToString(4, outPath.Length - 4);
return outPath.ToString();
}
// http://www.pinvoke.net/default.aspx/kernel32.createfile
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
static extern SafeFileHandle CreateFile(
[MarshalAs(UnmanagedType.LPTStr)] string filename,
[MarshalAs(UnmanagedType.U4)] FileAccess access,
[MarshalAs(UnmanagedType.U4)] FileShare share,
IntPtr securityAttributes, // optional SECURITY_ATTRIBUTES struct or IntPtr.Zero
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
IntPtr templateFile);
private const uint FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
public static string GetFinalPathName(string dirtyPath)
{
// use 0 for access so we can avoid error on our metadata-only query (see dwDesiredAccess docs on CreateFile)
// use FILE_FLAG_BACKUP_SEMANTICS for attributes so we can operate on directories (see Directories in remarks section for CreateFile docs)
using (var directoryHandle = CreateFile(
dirtyPath, 0, FileShare.ReadWrite | FileShare.Delete, IntPtr.Zero, FileMode.Open,
(FileAttributes)FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero))
{
if (directoryHandle.IsInvalid)
throw new Win32Exception(Marshal.GetLastWin32Error());
return GetFinalPathNameByHandle(directoryHandle);
}
}
I tried to avoid dll imports so the best way for me was to use System.Linq and the System.IO.Directory class.
For your example
Real path is: d:\src\File.txt
The user give me: D:\src\file.txt
Code for this:
using System.Linq;
public static class PathUtils
{
public static string RealPath(string inputPath)
{
return Directory.GetFiles(Path.GetDirectoryName(inputPath))
.FirstOrDefault(p => String.Equals(Path.GetFileName(p),
Path.GetFileName(inputPath), StringComparison.OrdinalIgnoreCase));
}
}
var p = PathUtils.RealPath(#"D:\src\file.txt");
Method should return the path "d:\src\File.txt" or "D:\src\File.txt".
Here is how I do it. Originally, I used to depend on GetFinalPathNameByHandle which is very good, but unfortunately, some custom file systems don't support it (of course NTFS does). I also tried NtQueryObject with ObjectNameInformation but again, they don't necessarily report the original file name.
So here is another "manual" way:
public static string GetRealPath(string fullPath)
{
if (fullPath == null)
return null; // invalid
var pos = fullPath.LastIndexOf(Path.DirectorySeparatorChar);
if (pos < 0 || pos == (fullPath.Length - 1))
return fullPath.ToUpperInvariant(); // drive letter
var dirPath = fullPath.Substring(0, pos);
var realPath = GetRealPath(dirPath); // go recursive, we want the final full path
if (realPath == null)
return null; // doesn't exist
var dir = new DirectoryInfo(realPath);
if (!dir.Exists)
return null; // doesn't exist
var fileName = fullPath.Substring(pos + 1);
if (fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) // avoid wildcard calls
return null;
return dir.EnumerateFileSystemInfos(fileName).FirstOrDefault()?.FullName; // may return null
}
On Windows, paths are case-insensitive. So both paths are equally real.
If you want to get some kind of a path with canonical capitalization (i. e. how Windows thinks it should be capitalized), you can call FindFirstFile() with the path as a mask, then take the full name of the found file. If the path is invalid, then you won't get a canonical name, natually.