Related
What will be analog of this code in PHP? I am not able to port this piece of code on PHP.
internal void GenerateKeyPair()
{
ecKey = new ECKey();
GeneratedPublicKey = new ECPublicKey()
{
X = ecKey.X,
Y = ecKey.Y,
CurveOId = ecKey.CurveOId
};
}
openssl_pkey_new() can generate a private key, see the Documentation for an example with private/public key usage.
If I have two DirectoryInfo objects, how can I compare them for semantic equality? For example, the following paths should all be considered equal to C:\temp:
C:\temp
C:\temp\
C:\temp\.
C:\temp\x\..\..\temp\.
The following may or may not be equal to C:\temp:
\temp if the current working directory is on drive C:\
temp if the current working directory is C:\
C:\temp.
C:\temp...\
If it's important to consider the current working directory, I can figure that out myself, so that's not that important. Trailing dots are stripped in windows, so those paths really should be equal - but they aren't stripped in unix, so under mono I'd expect other results.
Case sensitivity is optional. The paths may or may not exist, and the user may or may not have permissions to the path - I'd prefer a fast robust method that doesn't require any I/O (so no permission checking), but if there's something built-in I'd be happy with anything "good enough" too...
I realize that without I/O it's not possible to determine whether some intermediate storage layer happens to have mapped the same storage to the same file (and even with I/O, when things get messy enough it's likely impossible). However, it should be possible to at least positively identify paths that are equivalent, regardless of the underlying filesystem, i.e. paths that necessarily would resolve to the same file (if it exists) on all possible file-systems of a given type. The reason this is sometimes useful is (A) because I certainly want to check this first, before doing I/O, (B) I/O sometimes triggers problematic side-effects, and (C) various other software components sometimes mangle paths provided, and it's helpful to be able to compare in a way that's insensitive to most common transformations of equivalent paths, and finally (D) to prepare deployments it's useful to do some sanity checks beforehand, but those occur before the to-be-deployed-on system is even accessible.
GetFullPath seems to do the work, except for case difference (Path.GetFullPath("test") != Path.GetFullPath("TEST")) and trailing slash.
So, the following code should work fine:
String.Compare(
Path.GetFullPath(path1).TrimEnd('\\'),
Path.GetFullPath(path2).TrimEnd('\\'),
StringComparison.InvariantCultureIgnoreCase)
Or, if you want to start with DirectoryInfo:
String.Compare(
dirinfo1.FullName.TrimEnd('\\'),
dirinfo2.FullName.TrimEnd('\\'),
StringComparison.InvariantCultureIgnoreCase)
From this answer, this method can handle a few edge cases:
public static string NormalizePath(string path)
{
return Path.GetFullPath(new Uri(path).LocalPath)
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.ToUpperInvariant();
}
More details in the original answer. Call it like:
bool pathsEqual = NormalizePath(path1) == NormalizePath(path2);
Should work for both file and directory paths.
The question has been edited and clarified since it was originally asked and since this answer was originally posted. As the question currently stands, this answer below is not a correct answer. Essentially, the current question is asking for a purely textual path comparison, which is quite different from wanting to determine if two paths resolve to the same file system object. All the other answers, with the exception of Igor Korkhov's, are ultimately based on a textual comparison of two names.
If one actually wants to know when two paths resolve to the same file system object, you must do some IO. Trying to get two "normalized" names, that take in to account the myriad of possible ways of referencing the same file object, is next to impossible. There are issues such as: junctions, symbolic links, network file shares (referencing the same file object in different manners), etc. etc. In fact, every single answer above, with the exception of Igor Korkhov's, will absolutely give incorrect results in certain circumstances to the question "do these two paths reference the same file system object. (e.g. junctions, symbolic links, directory links, etc.)
The question specifically requested that the solution not require any I/O, but if you are going to deal with networked paths, you will absolutely need to do IO: there are cases where it is simply not possible to determine from any local path-string manipulation, whether two file references will reference the same physical file. (This can be easily understood as follows. Suppose a file server has a windows directory junction somewhere within a shared subtree. In this case, a file can be referenced either directly, or through the junction. But the junction resides on, and is resolved by, the file server, and so it is simply impossible for a client to determine, purely through local information, that the two referencing file names refer to the same physical file: the information is simply not available locally to the client. Thus one must absolutely do some minimal IO - e.g. open two file object handles - to determine if the references refer to the same physical file.)
The following solution does some IO, though very minimal, but correctly determines whether two file system references are semantically identical, i.e. reference the same file object. (if neither file specification refers to a valid file object, all bets are off):
public static bool AreDirsEqual(string dirName1, string dirName2, bool resolveJunctionaAndNetworkPaths = true)
{
if (string.IsNullOrEmpty(dirName1) || string.IsNullOrEmpty(dirName2))
return dirName1==dirName2;
dirName1 = NormalizePath(dirName1); //assume NormalizePath normalizes/fixes case and path separators to Path.DirectorySeparatorChar
dirName2 = NormalizePath(dirName2);
int i1 = dirName1.Length;
int i2 = dirName2.Length;
do
{
--i1; --i2;
if (i1 < 0 || i2 < 0)
return i1 < 0 && i2 < 0;
} while (dirName1[i1] == dirName2[i2]);//If you want to deal with international character sets, i.e. if NormalixePath does not fix case, this comparison must be tweaked
if( !resolveJunctionaAndNetworkPaths )
return false;
for(++i1, ++i2; i1 < dirName1.Length; ++i1, ++i2)
{
if (dirName1[i1] == Path.DirectorySeparatorChar)
{
dirName1 = dirName1.Substring(0, i1);
dirName2 = dirName1.Substring(0, i2);
break;
}
}
return AreFileSystemObjectsEqual(dirName1, dirName2);
}
public static bool AreFileSystemObjectsEqual(string dirName1, string dirName2)
{
//NOTE: we cannot lift the call to GetFileHandle out of this routine, because we _must_
// have both file handles open simultaneously in order for the objectFileInfo comparison
// to be guaranteed as valid.
using (SafeFileHandle directoryHandle1 = GetFileHandle(dirName1), directoryHandle2 = GetFileHandle(dirName2))
{
BY_HANDLE_FILE_INFORMATION? objectFileInfo1 = GetFileInfo(directoryHandle1);
BY_HANDLE_FILE_INFORMATION? objectFileInfo2 = GetFileInfo(directoryHandle2);
return objectFileInfo1 != null
&& objectFileInfo2 != null
&& (objectFileInfo1.Value.FileIndexHigh == objectFileInfo2.Value.FileIndexHigh)
&& (objectFileInfo1.Value.FileIndexLow == objectFileInfo2.Value.FileIndexLow)
&& (objectFileInfo1.Value.VolumeSerialNumber == objectFileInfo2.Value.VolumeSerialNumber);
}
}
static SafeFileHandle GetFileHandle(string dirName)
{
const int FILE_ACCESS_NEITHER = 0;
//const int FILE_SHARE_READ = 1;
//const int FILE_SHARE_WRITE = 2;
//const int FILE_SHARE_DELETE = 4;
const int FILE_SHARE_ANY = 7;//FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
const int CREATION_DISPOSITION_OPEN_EXISTING = 3;
const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
return CreateFile(dirName, FILE_ACCESS_NEITHER, FILE_SHARE_ANY, System.IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, System.IntPtr.Zero);
}
static BY_HANDLE_FILE_INFORMATION? GetFileInfo(SafeFileHandle directoryHandle)
{
BY_HANDLE_FILE_INFORMATION objectFileInfo;
if ((directoryHandle == null) || (!GetFileInformationByHandle(directoryHandle.DangerousGetHandle(), out objectFileInfo)))
{
return null;
}
return objectFileInfo;
}
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode,
IntPtr SecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[StructLayout(LayoutKind.Sequential)]
public struct BY_HANDLE_FILE_INFORMATION
{
public uint FileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
};
Note that in the above code I have included two lines like dirName1 = NormalizePath(dirName1); and have not specified what the function NormalizePath is. NormalizePath can be any path-normalization function - many have been provided in answers elsewhere in this question. Providing a reasonable NormalizePath function means that AreDirsEqual will give a reasonable answer even when the two input paths refer to non-existent file system objects, i.e. to paths that you simply want to compare on a string-level. ( Ishmaeel's comment above should be paid heed as well, and this code does not do that...)
(There may be subtle permissions issues with this code, if a user has only traversal permissions on some initial directories, I am not sure if the file system accesses required by AreFileSystemObjectsEqual are permitted. The parameter resolveJunctionaAndNetworkPaths at least allows the user to revert to pure textual comparison in this case...)
The idea for this came from a reply by Warren Stevens in a similar question I posted on SuperUser: https://superuser.com/a/881966/241981
There are some short comes to the implementation of paths in .NET. There are many complaints about it. Patrick Smacchia, the creator of NDepend, published an open source library that enables handling of common and complex path operations. If you do a lot of compare operations on paths in your application, this library might be useful to you.
It seems that P/Invoking GetFinalPathNameByHandle() would be the most reliable solution.
UPD: Oops, I didn't take into account your desire not to use any I/O
Microsoft has implemented similar methods, although they are not as useful as the answers above:
PathUtil.ArePathsEqual Method (which is just return string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase);)
PathUtil.Normalize Method
PathUtil.NormalizePath Method (which is just return PathUtil.Normalize(path);)
System.IO.Path.GetFullPath(pathA).Equals(System.IO.Path.GetFullPath(PathB));
The "Name" properties are equal. Take:
DirectoryInfo dir1 = new DirectoryInfo("C:\\Scratch");
DirectoryInfo dir2 = new DirectoryInfo("C:\\Scratch\\");
DirectoryInfo dir3 = new DirectoryInfo("C:\\Scratch\\4760");
DirectoryInfo dir4 = new DirectoryInfo("C:\\Scratch\\4760\\..\\");
dir1.Name == dir2.Name and dir2.Name == dir4.Name ("Scratch" in this case. dir3 == "4760".) It's only the FullName properties that are different.
You might be able to do a recursive method to examine the Name properties of each parent given your two DirectoryInfo classes to ensure the complete path is the same.
EDIT: does this work for your situation? Create a Console Application and paste this over the entire Program.cs file. Provide two DirectoryInfo objects to the AreEquals() function and it will return True if they're the same directory. You might be able to tweak this AreEquals() method to be an extension method on DirectoryInfo if you like, so you could just do myDirectoryInfo.IsEquals(myOtherDirectoryInfo);
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch"),
new DirectoryInfo("C:\\Scratch\\")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework"),
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\1033\\..\\..")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch\\"),
new DirectoryInfo("C:\\Scratch\\4760\\..\\..")));
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
private static bool AreEqual(DirectoryInfo dir1, DirectoryInfo dir2)
{
DirectoryInfo parent1 = dir1;
DirectoryInfo parent2 = dir2;
/* Build a list of parents */
List<string> folder1Parents = new List<string>();
List<string> folder2Parents = new List<string>();
while (parent1 != null)
{
folder1Parents.Add(parent1.Name);
parent1 = parent1.Parent;
}
while (parent2 != null)
{
folder2Parents.Add(parent2.Name);
parent2 = parent2.Parent;
}
/* Now compare the lists */
if (folder1Parents.Count != folder2Parents.Count)
{
// Cannot be the same - different number of parents
return false;
}
bool equal = true;
for (int i = 0; i < folder1Parents.Count && i < folder2Parents.Count; i++)
{
equal &= folder1Parents[i] == folder2Parents[i];
}
return equal;
}
}
}
You can use Minimatch, a port of Node.js' minimatch.
var mm = new Minimatcher(searchPattern, new Options { AllowWindowsPaths = true });
if (mm.IsMatch(somePath))
{
// The path matches! Do some cool stuff!
}
var matchingPaths = mm.Filter(allPaths);
See why the AllowWindowsPaths = true option is necessary:
On Windows-style paths
Minimatch's syntax was designed for Linux-style paths (with forward slashes only). In particular, it uses the backslash as an escape character, so it cannot simply accept Windows-style paths. My C# version preserves this behavior.
To suppress this, and allow both backslashes and forward slashes as path separators (in patterns or input), set the AllowWindowsPaths option:
var mm = new Minimatcher(searchPattern, new Options { AllowWindowsPaths = true });
Passing this option will disable escape characters entirely.
Nuget: http://www.nuget.org/packages/Minimatch/
GitHub: https://github.com/SLaks/Minimatch
using System;
using System.Collections.Generic;
using System.Text;
namespace EventAnalysis.IComparerImplementation
{
public sealed class FSChangeElemComparerByPath : IComparer<FSChangeElem>
{
public int Compare(FSChangeElem firstPath, FSChangeElem secondPath)
{
return firstPath.strObjectPath == null ?
(secondPath.strObjectPath == null ? 0 : -1) :
(secondPath.strObjectPath == null ? 1 : ComparerWrap(firstPath.strObjectPath, secondPath.strObjectPath));
}
private int ComparerWrap(string stringA, string stringB)
{
int length = 0;
int start = 0;
List<string> valueA = new List<string>();
List<string> valueB = new List<string>();
ListInit(ref valueA, stringA);
ListInit(ref valueB, stringB);
if (valueA.Count != valueB.Count)
{
length = (valueA.Count > valueB.Count)
? valueA.Count : valueB.Count;
if (valueA.Count != length)
{
for (int i = 0; i < length - valueA.Count; i++)
{
valueA.Add(string.Empty);
}
}
else
{
for (int i = 0; i < length - valueB.Count; i++)
{
valueB.Add(string.Empty);
}
}
}
else
length = valueA.Count;
return RecursiveComparing(valueA, valueB, length, start);
}
private void ListInit(ref List<string> stringCollection, string stringToList)
{
foreach (string s in stringToList.Remove(0, 2).Split('\\'))
{
stringCollection.Add(s);
}
}
private int RecursiveComparing(List<string> valueA, List<string> valueB, int length, int start)
{
int result = 0;
if (start != length)
{
if (valueA[start] == valueB[start])
{
result = RecursiveComparing(valueA, valueB, length, ++start);
}
else
{
result = String.Compare(valueA[start], valueB[start]);
}
}
else
return 0;
return result;
}
}
}
I used recursion to solve this problem for myself.
public bool PathEquals(string Path1, string Path2)
{
FileInfo f1 = new FileInfo(Path1.Trim('\\','/','.'));
FileInfo f2 = new FileInfo(Path2.Trim('\\', '/','.'));
if(f1.Name.ToLower() == f2.Name.ToLower())
{
return DirectoryEquals(f1.Directory, f2.Directory);
}
else
{
return false;
}
}
public bool DirectoryEquals(DirectoryInfo d1, DirectoryInfo d2)
{
if(d1.Name.ToLower() == d2.Name.ToLower())
{
if((d1.Parent != null) && (d2.Parent != null))
{
return DirectoryEquals(d1.Parent, d2.Parent);
}
else
{
return true;//C:\Temp1\Temp2 equals \Temp1\Temp2
//return (d1.Parent == null) && (d2.Parent == null);//C:\Temp1\Temp2 does not equal \Temp1\Temp2
}
}
else
{
return false;
}
}
Note: new FileInfo(path) returns a valid FileInfo even if path is not a file (the name field is equal to the directory name)
Thank you, #Andy Shellam and #VladV and #Eamon Nerbonne
I found the other solution:
private static bool AreEqual(DirectoryInfo dir1, DirectoryInfo dir2)
{
return AreEqual(dir1.FullName, dir2.FullName);
}
private static bool AreEqual(string folderPath1, string folderPath2)
{
folderPath1 = Path.GetFullPath(folderPath1);
folderPath2 = Path.GetFullPath(folderPath2);
if (folderPath1.Length == folderPath2.Length)
{
return string.Equals(folderPath1, folderPath2/*, StringComparison.OrdinalIgnoreCase*/);
}
else if (folderPath1.Length == folderPath2.Length + 1 && IsEndWithAltDirectorySeparatorChar(folderPath1))
{
// folderPath1 = #"F:\temp\"
// folderPath2 = #"F:\temp"
return folderPath1.Contains(folderPath2 /*, StringComparison.OrdinalIgnoreCase*/);
}
else if (folderPath1.Length + 1 == folderPath2.Length && IsEndWithAltDirectorySeparatorChar(folderPath2))
{
// folderPath1 = #"F:\temp"
// folderPath2 = #"F:\temp\"
return folderPath2.Contains(folderPath1 /*, StringComparison.OrdinalIgnoreCase*/);
}
return false;
static bool IsEndWithAltDirectorySeparatorChar(string path)
{
var lastChar = path[path.Length - 1];
return lastChar == Path.DirectorySeparatorChar;
}
}
It can work well.
static void Main(string[] args)
{
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch"),
new DirectoryInfo("C:\\Scratch\\")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework"),
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\1033\\..\\..")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch\\"),
new DirectoryInfo("C:\\Scratch\\4760\\..\\..")));
Debug.WriteLine(AreEqual(#"C:/Temp", #"C:\Temp2")); // False
Debug.WriteLine(AreEqual(#"C:\Temp\", #"C:\Temp2"));// False
Debug.WriteLine(AreEqual(#"C:\Temp\", #"C:\Temp")); // True
Debug.WriteLine(AreEqual(#"C:\Temp/", #"C:\Temp")); // True
Debug.WriteLine(AreEqual(#"C:/Temp/", #"C:\Temp\"));// True
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
bool equals = myDirectoryInfo1.FullName == myDirectoryInfo2.FullName;
?
bool Equals(string path1, string path2)
{
return new Uri(path1) == new Uri(path2);
}
Uri constructor normalizes the path.
I am using MD5 hashing first time, I am trying to create a token to secure my web-services. I have found three different md5 hashing method for Android, IOS and C#. Before I call any webservice, I create a token and send it as a parameter. Then, when I get the token in service side, I create a token with the same algorithm in C# too and compare those two tokens. If the tokens are the same, I permit to the process. If not, I throw an exeption. My problem is, tokens are always different. I suppose that the difference of md5 creation methods causes this problem.
MD5 method in the C# code:
public static string MD5(string stringToEncrypted)
{
// step 1, calculate MD5 hash from input
var md5 = System.Security.Cryptography.MD5.Create();
byte[] inputBytes = System.Text.Encoding.ASCII.GetBytes(stringToEncrypted);
byte[] hash = md5.ComputeHash(inputBytes);
// step 2, convert byte array to hex string
var sb = new StringBuilder();
for (int i = 0; i < hash.Length; i++)
{
sb.Append(hash[i].ToString("X2"));
}
return sb.ToString();
}
In Swift Code:
extension String
{
var md5: String!
{
let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
let digestLen = Int(CC_MD5_DIGEST_LENGTH)
let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen)
CC_MD5(str!, strLen, result)
var hash = NSMutableString()
for i in 0..<digestLen
{
hash.appendFormat("%02x", result[i])
}
result.destroy()
return String(format: hash)
}
}
In Android Code:
public static final String md5(final String stringToEncrypted)
{
final String MD5 = "MD5";
try
{
// Create MD5 Hash
MessageDigest digest = java.security.MessageDigest.getInstance(MD5);
digest.update(stringToEncrypted.getBytes());
byte messageDigest[] = digest.digest();
// Create Hex String
StringBuilder hexString = new StringBuilder();
for (byte aMessageDigest : messageDigest)
{
String h = Integer.toHexString(0xFF & aMessageDigest);
while (h.length() < 2)
h = "0" + h;
hexString.append(h);
}
return hexString.toString();
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
return "";
}
In Android using: h = "0" + h;
In IOS using: hash.appendFormat("%02x", result[i])
In C# using: sb.Append(hash[i].ToString("X2"));
Do these differences cause this problem ?
Thank you for your answers,
Best regards
Code example from SO Answer
func doSha256(#dataIn:NSData) -> NSData {
var shaOut: NSMutableData! = NSMutableData(length: Int(CC_SHA256_DIGEST_LENGTH));
CC_SHA256(dataIn.bytes, CC_LONG(dataIn.length), UnsafeMutablePointer<UInt8>(shaOut.mutableBytes));
return shaOut;
}
Obviously just change the constants for other hash methods.
If you want another format, say Base64 or hex put those conversions in a wrapper method that calls this method. It is better not to co-mingle methods, allow each to do a single thing. (Single Responsibility Principle) It also allows for easier testing and debugging.
I'm using the WebBrowser class to open document, change values, save and print. The problem is, that it prints the document including the header("Page 1 of 1") and footer(root of the document + date)
I looked at the documentation and didn't find a way to remove them. Is it even possible using WebBrowser or should I look for alternatives?
There is a solution, probably not as cleaner as it could have been. Since WebBrowser inhertis it's settings from Internet Explorer it is possible to change the values in the registry. Luckily the values are under HKCU so no administration permissions are needed.
Take a look at https://stackoverflow.com/a/1321314/1630928
The trick to doing this is to pass a Variant containing a ByRef SafeArray of Variants to the WebBrowser control. I haven't figured out how to do it from C#. Here's someone else who was working on the same problem who resorted to using managed C++
http://www.limilabs.com/blog/printing-in-webbrowser-control-custom-header-and-footer
Not a C#, but here's C++ code that I came up with based on a now defunct KB267240. It will remove the header and the footer while printing:
BOOL bRes = FALSE;
//Get IWebBrowser2 from your IE control
CComPtr<IWebBrowser2> pWebBrowser = this->GetIWebBrowser2();
if(pWebBrowser)
{
HRESULT hr;
COleVariant varNull;
SAFEARRAYBOUND psabBounds[1];
SAFEARRAY *psaHeadFoot;
hr = S_OK;
VARIANT vArg;
BOOL bGot_vArg = FALSE;
VARIANT vHeadStr, vFootStr;
long rgIndices;
VariantInit(&vHeadStr);
VariantInit(&vFootStr);
// Initialize header and footer parameters to send to ExecWB().
psabBounds[0].lLbound = 0;
psabBounds[0].cElements = 3;
psaHeadFoot = SafeArrayCreate(VT_VARIANT, 1, psabBounds);
if(psaHeadFoot)
{
// Argument 1: Header
vHeadStr.vt = VT_BSTR;
vHeadStr.bstrVal = SysAllocString(L" "); //Must be at least one space
if (vHeadStr.bstrVal)
{
// Argument 2: Footer
vFootStr.vt = VT_BSTR;
vFootStr.bstrVal = SysAllocString(L" "); //Must be at least one space
if(vFootStr.bstrVal)
{
rgIndices = 0;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&vHeadStr));
rgIndices = 1;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&vFootStr));
rgIndices = 2;
SafeArrayPutElement(psaHeadFoot, &rgIndices, static_cast<void *>(&varNull)); //Set stream to NULL as we don't need it
//NOTE: Currently, the SAFEARRAY variant must be passed by using
// the VT_BYREF vartype when you call the ExecWeb method.
VariantInit(&vArg);
vArg.vt = VT_ARRAY | VT_BYREF;
vArg.parray = psaHeadFoot;
//Got it
bGot_vArg = TRUE;
}
}
}
//Did we get all the vars?
if(bGot_vArg)
{
if(SUCCEEDED(hr = pWebBrowser->ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, &vArg, NULL)))
{
//All good
bRes = TRUE;
}
}
else
{
//Use fallback (that will keep the footer & header)
if(SUCCEEDED(hr = pWebBrowser->ExecWB(OLECMDID_PRINT, OLECMDEXECOPT_PROMPTUSER, varNull, varNull)))
{
//Printed via fallback
bRes = TRUE;
}
}
//Clean up
VariantClear(&vHeadStr);
VariantClear(&vFootStr);
if(psaHeadFoot)
{
SafeArrayDestroy(psaHeadFoot);
psaHeadFoot = NULL;
}
}
If I have two DirectoryInfo objects, how can I compare them for semantic equality? For example, the following paths should all be considered equal to C:\temp:
C:\temp
C:\temp\
C:\temp\.
C:\temp\x\..\..\temp\.
The following may or may not be equal to C:\temp:
\temp if the current working directory is on drive C:\
temp if the current working directory is C:\
C:\temp.
C:\temp...\
If it's important to consider the current working directory, I can figure that out myself, so that's not that important. Trailing dots are stripped in windows, so those paths really should be equal - but they aren't stripped in unix, so under mono I'd expect other results.
Case sensitivity is optional. The paths may or may not exist, and the user may or may not have permissions to the path - I'd prefer a fast robust method that doesn't require any I/O (so no permission checking), but if there's something built-in I'd be happy with anything "good enough" too...
I realize that without I/O it's not possible to determine whether some intermediate storage layer happens to have mapped the same storage to the same file (and even with I/O, when things get messy enough it's likely impossible). However, it should be possible to at least positively identify paths that are equivalent, regardless of the underlying filesystem, i.e. paths that necessarily would resolve to the same file (if it exists) on all possible file-systems of a given type. The reason this is sometimes useful is (A) because I certainly want to check this first, before doing I/O, (B) I/O sometimes triggers problematic side-effects, and (C) various other software components sometimes mangle paths provided, and it's helpful to be able to compare in a way that's insensitive to most common transformations of equivalent paths, and finally (D) to prepare deployments it's useful to do some sanity checks beforehand, but those occur before the to-be-deployed-on system is even accessible.
GetFullPath seems to do the work, except for case difference (Path.GetFullPath("test") != Path.GetFullPath("TEST")) and trailing slash.
So, the following code should work fine:
String.Compare(
Path.GetFullPath(path1).TrimEnd('\\'),
Path.GetFullPath(path2).TrimEnd('\\'),
StringComparison.InvariantCultureIgnoreCase)
Or, if you want to start with DirectoryInfo:
String.Compare(
dirinfo1.FullName.TrimEnd('\\'),
dirinfo2.FullName.TrimEnd('\\'),
StringComparison.InvariantCultureIgnoreCase)
From this answer, this method can handle a few edge cases:
public static string NormalizePath(string path)
{
return Path.GetFullPath(new Uri(path).LocalPath)
.TrimEnd(Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar)
.ToUpperInvariant();
}
More details in the original answer. Call it like:
bool pathsEqual = NormalizePath(path1) == NormalizePath(path2);
Should work for both file and directory paths.
The question has been edited and clarified since it was originally asked and since this answer was originally posted. As the question currently stands, this answer below is not a correct answer. Essentially, the current question is asking for a purely textual path comparison, which is quite different from wanting to determine if two paths resolve to the same file system object. All the other answers, with the exception of Igor Korkhov's, are ultimately based on a textual comparison of two names.
If one actually wants to know when two paths resolve to the same file system object, you must do some IO. Trying to get two "normalized" names, that take in to account the myriad of possible ways of referencing the same file object, is next to impossible. There are issues such as: junctions, symbolic links, network file shares (referencing the same file object in different manners), etc. etc. In fact, every single answer above, with the exception of Igor Korkhov's, will absolutely give incorrect results in certain circumstances to the question "do these two paths reference the same file system object. (e.g. junctions, symbolic links, directory links, etc.)
The question specifically requested that the solution not require any I/O, but if you are going to deal with networked paths, you will absolutely need to do IO: there are cases where it is simply not possible to determine from any local path-string manipulation, whether two file references will reference the same physical file. (This can be easily understood as follows. Suppose a file server has a windows directory junction somewhere within a shared subtree. In this case, a file can be referenced either directly, or through the junction. But the junction resides on, and is resolved by, the file server, and so it is simply impossible for a client to determine, purely through local information, that the two referencing file names refer to the same physical file: the information is simply not available locally to the client. Thus one must absolutely do some minimal IO - e.g. open two file object handles - to determine if the references refer to the same physical file.)
The following solution does some IO, though very minimal, but correctly determines whether two file system references are semantically identical, i.e. reference the same file object. (if neither file specification refers to a valid file object, all bets are off):
public static bool AreDirsEqual(string dirName1, string dirName2, bool resolveJunctionaAndNetworkPaths = true)
{
if (string.IsNullOrEmpty(dirName1) || string.IsNullOrEmpty(dirName2))
return dirName1==dirName2;
dirName1 = NormalizePath(dirName1); //assume NormalizePath normalizes/fixes case and path separators to Path.DirectorySeparatorChar
dirName2 = NormalizePath(dirName2);
int i1 = dirName1.Length;
int i2 = dirName2.Length;
do
{
--i1; --i2;
if (i1 < 0 || i2 < 0)
return i1 < 0 && i2 < 0;
} while (dirName1[i1] == dirName2[i2]);//If you want to deal with international character sets, i.e. if NormalixePath does not fix case, this comparison must be tweaked
if( !resolveJunctionaAndNetworkPaths )
return false;
for(++i1, ++i2; i1 < dirName1.Length; ++i1, ++i2)
{
if (dirName1[i1] == Path.DirectorySeparatorChar)
{
dirName1 = dirName1.Substring(0, i1);
dirName2 = dirName1.Substring(0, i2);
break;
}
}
return AreFileSystemObjectsEqual(dirName1, dirName2);
}
public static bool AreFileSystemObjectsEqual(string dirName1, string dirName2)
{
//NOTE: we cannot lift the call to GetFileHandle out of this routine, because we _must_
// have both file handles open simultaneously in order for the objectFileInfo comparison
// to be guaranteed as valid.
using (SafeFileHandle directoryHandle1 = GetFileHandle(dirName1), directoryHandle2 = GetFileHandle(dirName2))
{
BY_HANDLE_FILE_INFORMATION? objectFileInfo1 = GetFileInfo(directoryHandle1);
BY_HANDLE_FILE_INFORMATION? objectFileInfo2 = GetFileInfo(directoryHandle2);
return objectFileInfo1 != null
&& objectFileInfo2 != null
&& (objectFileInfo1.Value.FileIndexHigh == objectFileInfo2.Value.FileIndexHigh)
&& (objectFileInfo1.Value.FileIndexLow == objectFileInfo2.Value.FileIndexLow)
&& (objectFileInfo1.Value.VolumeSerialNumber == objectFileInfo2.Value.VolumeSerialNumber);
}
}
static SafeFileHandle GetFileHandle(string dirName)
{
const int FILE_ACCESS_NEITHER = 0;
//const int FILE_SHARE_READ = 1;
//const int FILE_SHARE_WRITE = 2;
//const int FILE_SHARE_DELETE = 4;
const int FILE_SHARE_ANY = 7;//FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE
const int CREATION_DISPOSITION_OPEN_EXISTING = 3;
const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
return CreateFile(dirName, FILE_ACCESS_NEITHER, FILE_SHARE_ANY, System.IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, System.IntPtr.Zero);
}
static BY_HANDLE_FILE_INFORMATION? GetFileInfo(SafeFileHandle directoryHandle)
{
BY_HANDLE_FILE_INFORMATION objectFileInfo;
if ((directoryHandle == null) || (!GetFileInformationByHandle(directoryHandle.DangerousGetHandle(), out objectFileInfo)))
{
return null;
}
return objectFileInfo;
}
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode,
IntPtr SecurityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetFileInformationByHandle(IntPtr hFile, out BY_HANDLE_FILE_INFORMATION lpFileInformation);
[StructLayout(LayoutKind.Sequential)]
public struct BY_HANDLE_FILE_INFORMATION
{
public uint FileAttributes;
public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
};
Note that in the above code I have included two lines like dirName1 = NormalizePath(dirName1); and have not specified what the function NormalizePath is. NormalizePath can be any path-normalization function - many have been provided in answers elsewhere in this question. Providing a reasonable NormalizePath function means that AreDirsEqual will give a reasonable answer even when the two input paths refer to non-existent file system objects, i.e. to paths that you simply want to compare on a string-level. ( Ishmaeel's comment above should be paid heed as well, and this code does not do that...)
(There may be subtle permissions issues with this code, if a user has only traversal permissions on some initial directories, I am not sure if the file system accesses required by AreFileSystemObjectsEqual are permitted. The parameter resolveJunctionaAndNetworkPaths at least allows the user to revert to pure textual comparison in this case...)
The idea for this came from a reply by Warren Stevens in a similar question I posted on SuperUser: https://superuser.com/a/881966/241981
There are some short comes to the implementation of paths in .NET. There are many complaints about it. Patrick Smacchia, the creator of NDepend, published an open source library that enables handling of common and complex path operations. If you do a lot of compare operations on paths in your application, this library might be useful to you.
It seems that P/Invoking GetFinalPathNameByHandle() would be the most reliable solution.
UPD: Oops, I didn't take into account your desire not to use any I/O
Microsoft has implemented similar methods, although they are not as useful as the answers above:
PathUtil.ArePathsEqual Method (which is just return string.Equals(path1, path2, StringComparison.OrdinalIgnoreCase);)
PathUtil.Normalize Method
PathUtil.NormalizePath Method (which is just return PathUtil.Normalize(path);)
System.IO.Path.GetFullPath(pathA).Equals(System.IO.Path.GetFullPath(PathB));
The "Name" properties are equal. Take:
DirectoryInfo dir1 = new DirectoryInfo("C:\\Scratch");
DirectoryInfo dir2 = new DirectoryInfo("C:\\Scratch\\");
DirectoryInfo dir3 = new DirectoryInfo("C:\\Scratch\\4760");
DirectoryInfo dir4 = new DirectoryInfo("C:\\Scratch\\4760\\..\\");
dir1.Name == dir2.Name and dir2.Name == dir4.Name ("Scratch" in this case. dir3 == "4760".) It's only the FullName properties that are different.
You might be able to do a recursive method to examine the Name properties of each parent given your two DirectoryInfo classes to ensure the complete path is the same.
EDIT: does this work for your situation? Create a Console Application and paste this over the entire Program.cs file. Provide two DirectoryInfo objects to the AreEquals() function and it will return True if they're the same directory. You might be able to tweak this AreEquals() method to be an extension method on DirectoryInfo if you like, so you could just do myDirectoryInfo.IsEquals(myOtherDirectoryInfo);
using System;
using System.Diagnostics;
using System.IO;
using System.Collections.Generic;
namespace ConsoleApplication3
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch"),
new DirectoryInfo("C:\\Scratch\\")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework"),
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\1033\\..\\..")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch\\"),
new DirectoryInfo("C:\\Scratch\\4760\\..\\..")));
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
private static bool AreEqual(DirectoryInfo dir1, DirectoryInfo dir2)
{
DirectoryInfo parent1 = dir1;
DirectoryInfo parent2 = dir2;
/* Build a list of parents */
List<string> folder1Parents = new List<string>();
List<string> folder2Parents = new List<string>();
while (parent1 != null)
{
folder1Parents.Add(parent1.Name);
parent1 = parent1.Parent;
}
while (parent2 != null)
{
folder2Parents.Add(parent2.Name);
parent2 = parent2.Parent;
}
/* Now compare the lists */
if (folder1Parents.Count != folder2Parents.Count)
{
// Cannot be the same - different number of parents
return false;
}
bool equal = true;
for (int i = 0; i < folder1Parents.Count && i < folder2Parents.Count; i++)
{
equal &= folder1Parents[i] == folder2Parents[i];
}
return equal;
}
}
}
You can use Minimatch, a port of Node.js' minimatch.
var mm = new Minimatcher(searchPattern, new Options { AllowWindowsPaths = true });
if (mm.IsMatch(somePath))
{
// The path matches! Do some cool stuff!
}
var matchingPaths = mm.Filter(allPaths);
See why the AllowWindowsPaths = true option is necessary:
On Windows-style paths
Minimatch's syntax was designed for Linux-style paths (with forward slashes only). In particular, it uses the backslash as an escape character, so it cannot simply accept Windows-style paths. My C# version preserves this behavior.
To suppress this, and allow both backslashes and forward slashes as path separators (in patterns or input), set the AllowWindowsPaths option:
var mm = new Minimatcher(searchPattern, new Options { AllowWindowsPaths = true });
Passing this option will disable escape characters entirely.
Nuget: http://www.nuget.org/packages/Minimatch/
GitHub: https://github.com/SLaks/Minimatch
using System;
using System.Collections.Generic;
using System.Text;
namespace EventAnalysis.IComparerImplementation
{
public sealed class FSChangeElemComparerByPath : IComparer<FSChangeElem>
{
public int Compare(FSChangeElem firstPath, FSChangeElem secondPath)
{
return firstPath.strObjectPath == null ?
(secondPath.strObjectPath == null ? 0 : -1) :
(secondPath.strObjectPath == null ? 1 : ComparerWrap(firstPath.strObjectPath, secondPath.strObjectPath));
}
private int ComparerWrap(string stringA, string stringB)
{
int length = 0;
int start = 0;
List<string> valueA = new List<string>();
List<string> valueB = new List<string>();
ListInit(ref valueA, stringA);
ListInit(ref valueB, stringB);
if (valueA.Count != valueB.Count)
{
length = (valueA.Count > valueB.Count)
? valueA.Count : valueB.Count;
if (valueA.Count != length)
{
for (int i = 0; i < length - valueA.Count; i++)
{
valueA.Add(string.Empty);
}
}
else
{
for (int i = 0; i < length - valueB.Count; i++)
{
valueB.Add(string.Empty);
}
}
}
else
length = valueA.Count;
return RecursiveComparing(valueA, valueB, length, start);
}
private void ListInit(ref List<string> stringCollection, string stringToList)
{
foreach (string s in stringToList.Remove(0, 2).Split('\\'))
{
stringCollection.Add(s);
}
}
private int RecursiveComparing(List<string> valueA, List<string> valueB, int length, int start)
{
int result = 0;
if (start != length)
{
if (valueA[start] == valueB[start])
{
result = RecursiveComparing(valueA, valueB, length, ++start);
}
else
{
result = String.Compare(valueA[start], valueB[start]);
}
}
else
return 0;
return result;
}
}
}
I used recursion to solve this problem for myself.
public bool PathEquals(string Path1, string Path2)
{
FileInfo f1 = new FileInfo(Path1.Trim('\\','/','.'));
FileInfo f2 = new FileInfo(Path2.Trim('\\', '/','.'));
if(f1.Name.ToLower() == f2.Name.ToLower())
{
return DirectoryEquals(f1.Directory, f2.Directory);
}
else
{
return false;
}
}
public bool DirectoryEquals(DirectoryInfo d1, DirectoryInfo d2)
{
if(d1.Name.ToLower() == d2.Name.ToLower())
{
if((d1.Parent != null) && (d2.Parent != null))
{
return DirectoryEquals(d1.Parent, d2.Parent);
}
else
{
return true;//C:\Temp1\Temp2 equals \Temp1\Temp2
//return (d1.Parent == null) && (d2.Parent == null);//C:\Temp1\Temp2 does not equal \Temp1\Temp2
}
}
else
{
return false;
}
}
Note: new FileInfo(path) returns a valid FileInfo even if path is not a file (the name field is equal to the directory name)
Thank you, #Andy Shellam and #VladV and #Eamon Nerbonne
I found the other solution:
private static bool AreEqual(DirectoryInfo dir1, DirectoryInfo dir2)
{
return AreEqual(dir1.FullName, dir2.FullName);
}
private static bool AreEqual(string folderPath1, string folderPath2)
{
folderPath1 = Path.GetFullPath(folderPath1);
folderPath2 = Path.GetFullPath(folderPath2);
if (folderPath1.Length == folderPath2.Length)
{
return string.Equals(folderPath1, folderPath2/*, StringComparison.OrdinalIgnoreCase*/);
}
else if (folderPath1.Length == folderPath2.Length + 1 && IsEndWithAltDirectorySeparatorChar(folderPath1))
{
// folderPath1 = #"F:\temp\"
// folderPath2 = #"F:\temp"
return folderPath1.Contains(folderPath2 /*, StringComparison.OrdinalIgnoreCase*/);
}
else if (folderPath1.Length + 1 == folderPath2.Length && IsEndWithAltDirectorySeparatorChar(folderPath2))
{
// folderPath1 = #"F:\temp"
// folderPath2 = #"F:\temp\"
return folderPath2.Contains(folderPath1 /*, StringComparison.OrdinalIgnoreCase*/);
}
return false;
static bool IsEndWithAltDirectorySeparatorChar(string path)
{
var lastChar = path[path.Length - 1];
return lastChar == Path.DirectorySeparatorChar;
}
}
It can work well.
static void Main(string[] args)
{
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch"),
new DirectoryInfo("C:\\Scratch\\")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework"),
new DirectoryInfo("C:\\Windows\\Microsoft.NET\\Framework\\v3.5\\1033\\..\\..")));
Console.WriteLine(AreEqual(
new DirectoryInfo("C:\\Scratch\\"),
new DirectoryInfo("C:\\Scratch\\4760\\..\\..")));
Debug.WriteLine(AreEqual(#"C:/Temp", #"C:\Temp2")); // False
Debug.WriteLine(AreEqual(#"C:\Temp\", #"C:\Temp2"));// False
Debug.WriteLine(AreEqual(#"C:\Temp\", #"C:\Temp")); // True
Debug.WriteLine(AreEqual(#"C:\Temp/", #"C:\Temp")); // True
Debug.WriteLine(AreEqual(#"C:/Temp/", #"C:\Temp\"));// True
Console.WriteLine("Press ENTER to continue");
Console.ReadLine();
}
bool equals = myDirectoryInfo1.FullName == myDirectoryInfo2.FullName;
?
bool Equals(string path1, string path2)
{
return new Uri(path1) == new Uri(path2);
}
Uri constructor normalizes the path.