I have an service to move files from a working folder to backup folder. The folders are on a network share, so at times we will open a file, using something like notepad, to look at it. People are not (well, shouldn't) be editing, just looking.
When we try to move the file, I get permission denied. I'm looking for a way in C# to force remove a file lock, so the service can move the file to the backup folder.
You have to use P/Invoke. These are the functions you care about:
[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 NetFileClose(string servername, int id);
[DllImport("Netapi32.dll", SetLastError = true)]
static extern int NetApiBufferFree(IntPtr buffer);
Here's some code similar to what I've used with success:
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
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;
}
private static FILE_INFO_3[] GetLockedFiles(string server, string path)
{
const int MAX_PREFERRED_LENGTH = -1;
int dwReadEntries;
int dwTotalEntries;
IntPtr pBuffer = IntPtr.Zero;
FILE_INFO_3 pCurrent = new FILE_INFO_3();
List<FILE_INFO_3> files = new List<FILE_INFO_3>();
int dwStatus = NetFileEnum(server, path, 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));
files.Add(pCurrent);
}
}
NetApiBufferFree(pBuffer);
return files.ToArray();
}
static void Main(string[] args)
{
FILE_INFO_3[] lockedFiles = GetLockedFiles("someservername", #"C:\somepath");
foreach (FILE_INFO_3 lockedFile in lockedFiles)
{
int dwStatus = NetFileClose(_serverName, lockedFile.fi3_id);
// Check dwStatus for success here
}
}
EDIT: As noted by the OP in the comments below, when compiling as 64-bit, you need to use ToInt64 instead of ToInt32. More information can be found here.
Related
Attempting to retrieve a large list of open files from a file server returns the ERROR_MORE_DATA value (Error number 234), but works fine when dealing with only a small list of files (seems to return around 84 entries). This code is based upon the example at: http://pinvoke.net/default.aspx/netapi32/NetFileEnum.html
Most examples I have found don't really touch on how to handle a large number of files. From my understanding, this has something to do with the resume_handle, however I'm not sure what needs to be done. Do I need to somehow call this method in a loop?
Code is as follows:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;
namespace OpenFiles
{
class Program
{
public static string computername = "computername";
static void Main(string[] args)
{
List<string> theFileList = NativeMethods.GetFiles(computername);
foreach (string file in theFileList)
{
Console.WriteLine(file);
}
}
}
static class NativeMethods
{
[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
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
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;
}
[DllImport("Netapi32.dll", SetLastError = true)]
static extern int NetApiBufferFree(IntPtr Buffer);
public static List<string> GetFiles(string Computername)
{
const int MAX_PREFERRED_LENGTH = -1;
int dwReadEntries;
int dwTotalEntries;
IntPtr pBuffer = IntPtr.Zero;
FILE_INFO_3 pCurrent = new FILE_INFO_3();
List<string> fileList = new List<string>();
int dwStatus = NetFileEnum(Computername, null, 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));
string fileInfo = pCurrent.fi3_id + "," +
pCurrent.fi3_num_locks + "," +
pCurrent.fi3_pathname + "," +
pCurrent.fi3_permission + "," +
pCurrent.fi3_username;
fileList.Add(fileInfo);
}
NetApiBufferFree(pBuffer);
}
else
{
Console.WriteLine("error: " + dwStatus);
}
return fileList;
}
}
}
In my limited experience a very large number of results can be larger than the max buffer. In this case a more data response is given and instructs us to call again with the provided resume handle. In your example, the resume handle will not be changed because the DllImport signature doesn't define it as an out parameter. Using the resume handle result from the first call (passing in zero means first call) allows you to receive the next batch. Loop until you receive a success response or some other error.
Be sure to fix the issue where the NetFileEnum signature is defined.
The resume handle is not defined with an out so cannot be changed by the called function.
Try the following DLL Import signature instead:
[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,
out IntPtr resume_handle
);
You should be able to re-call NetFileEnum with the resulting resume handle multiple times when you get a more data response.
Anyway of checking, in C#, that two files (hard links) point to the same inode? And also get the count of this inode, in case there are more than two... ?
You can get count of hard links pointing to the node using GetFileInformationByHandle function. For example:
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool GetFileInformationByHandle(
SafeFileHandle hFile,
out BY_HANDLE_FILE_INFORMATION lpFileInformation
);
[StructLayout(LayoutKind.Sequential)]
struct BY_HANDLE_FILE_INFORMATION {
public uint FileAttributes;
public FILETIME CreationTime;
public FILETIME LastAccessTime;
public FILETIME LastWriteTime;
public uint VolumeSerialNumber;
public uint FileSizeHigh;
public uint FileSizeLow;
public uint NumberOfLinks;
public uint FileIndexHigh;
public uint FileIndexLow;
}
// then in another place
using (var fs = File.OpenRead("path to your file")) {
BY_HANDLE_FILE_INFORMATION info;
GetFileInformationByHandle(fs.SafeFileHandle, out info);
var numberOfLinks = info.NumberOfLinks;
}
To get what files they are pointing to, you will need another win api functions: FindFirstFileNameW and FineNextFileNameW. Use them like this:
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern IntPtr FindFirstFileNameW(
string lpFileName,
uint dwFlags,
ref uint stringLength,
StringBuilder fileName);
[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
static extern bool FindNextFileNameW(
IntPtr hFindStream,
ref uint stringLength,
StringBuilder fileName);
[DllImport("kernel32.dll", SetLastError = true)]
static extern bool FindClose(IntPtr fFindHandle);
public static string[] GetFileHardLinks(string filePath) {
// first get drive letter
var drive = new DriveInfo(Path.GetPathRoot(filePath));
var result = new List<string>();
// buffer for return value
var sb = new StringBuilder(256);
// length of buffer
uint sbLength = 256;
// third argument contains reference to buffer length (buffer is StringBuilder).
// it's a reference because if it's too small, call returns an error and will put required length there instead
IntPtr findHandle = FindFirstFileNameW(filePath, 0, ref sbLength, sb);
// returns -1 on error
if (findHandle.ToInt64() != -1) {
do {
// combine the result with drive letter (it comes without it)
result.Add(Path.Combine(drive.RootDirectory.FullName, sb.ToString().TrimStart(new [] { Path.DirectorySeparatorChar, Path.AltDirectorySeparatorChar})));
sb.Clear();
sbLength = 256;
// and repeat
} while (FindNextFileNameW(findHandle, ref sbLength, sb));
FindClose(findHandle);
return result.ToArray();
}
return null;
}
This code might be not production ready, so take care. But it should at least give you an idea. If you will use it - carefully read what those function return on errors and act accordingly (for example, handle the case when buffer length is not enough, or just use larger buffer than 256).
Does anybody know how can get real path from symlink file or folder? Thank you!
Hello guys after my research I found this solution for how to get real path of a Symlink. If you have a created symlink and want to check where is the real pointer of this file or folder. If someone have better way to write it please share.
[DllImport("kernel32.dll", EntryPoint = "CreateFileW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern SafeFileHandle CreateFile(string lpFileName, int dwDesiredAccess, int dwShareMode, IntPtr securityAttributes, int dwCreationDisposition, int dwFlagsAndAttributes, IntPtr hTemplateFile);
[DllImport("kernel32.dll", EntryPoint = "GetFinalPathNameByHandleW", CharSet = CharSet.Unicode, SetLastError = true)]
private static extern int GetFinalPathNameByHandle([In] SafeFileHandle hFile, [Out] StringBuilder lpszFilePath, [In] int cchFilePath, [In] int dwFlags);
private const int CREATION_DISPOSITION_OPEN_EXISTING = 3;
private const int FILE_FLAG_BACKUP_SEMANTICS = 0x02000000;
public static string GetRealPath(string path)
{
if (!Directory.Exists(path) && !File.Exists(path))
{
throw new IOException("Path not found");
}
SafeFileHandle directoryHandle = CreateFile(path, 0, 2, IntPtr.Zero, CREATION_DISPOSITION_OPEN_EXISTING, FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero); //Handle file / folder
if (directoryHandle.IsInvalid)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
StringBuilder result = new StringBuilder(512);
int mResult = GetFinalPathNameByHandle(directoryHandle, result, result.Capacity, 0);
if (mResult < 0)
{
throw new Win32Exception(Marshal.GetLastWin32Error());
}
if (result.Length >= 4 && result[0] == '\\' && result[1] == '\\' && result[2] == '?' && result[3] == '\\')
{
return result.ToString().Substring(4); // "\\?\" remove
}
return result.ToString();
}
The search term RpcMgmtEpEltInqNext on both Stackoverflow and PInvoke.net yields zero results, so this should be worth asking. I've been fiddling around on MSDN and looking through Win SDK *.h files all day, and feeling a bit out of my element.
I'm basically attempting to query the MSRPC endpoint mapper with managed code. Here is what I have so far:
[DllImport("Rpcrt4.dll", CharSet = CharSet.Auto)]
public static extern int RpcBindingFromStringBinding(string StringBinding, out IntPtr Binding);
[DllImport("Rpcrt4.dll")]
public static extern int RpcBindingFree(ref IntPtr Binding);
[DllImport("Rpcrt4.dll", CharSet = CharSet.Auto)]
public static extern int RpcMgmtEpEltInqBegin(IntPtr EpBinding,
int InquiryType, // 0x00000000 = RPC_C_EP_ALL_ELTS
int IfId,
int VersOption,
string ObjectUuid,
out IntPtr InquiryContext);
[DllImport("Rpcrt4.dll", CharSet = CharSet.Auto)]
public static extern int RpcMgmtEpEltInqNext(ref IntPtr InquiryContext,
out int IfId,
out IntPtr Binding,
out string ObjectUuid,
out string Annotation);
public static List<int> QueryEPM(string host)
{
List<int> ports = new List<int>();
int retCode = 0; // RPC_S_OK
IntPtr bindingHandle = IntPtr.Zero;
IntPtr inquiryContext = IntPtr.Zero;
IntPtr elementBindingHandle = IntPtr.Zero;
int elementIfId = 0;
string elementUuid = string.Empty;
string elementAnnotation = string.Empty;
try
{
retCode = RpcBindingFromStringBinding("ncacn_ip_tcp:" + host, out bindingHandle);
if (retCode != 0)
throw new Exception("RpcBindingFromStringBinding: " + retCode);
retCode = RpcMgmtEpEltInqBegin(bindingHandle, 0, 0, 0, string.Empty, out inquiryContext);
if (retCode != 0)
throw new Exception("RpcMgmtEpEltInqBegin: " + retCode);
retCode = RpcMgmtEpEltInqNext (ref inquiryContext, out elementIfId, out elementBindingHandle, out elementUuid, out elementAnnotation);
if (retCode != 0)
throw new Exception("RpcMgmtEpEltInqNext: " + retCode);
}
The above code isn't complete, but it illustrates my point. The code consistently returns:
RpcMgmtEpEltIngNext: 87
87 meaning Parameter is Incorrect according to here.
So I'm basically stumped at this point, and I'm sure it's because of my extremely crappy PInvoke code.
The p/invoke declaration is wrong. It needs to be:
[DllImport("Rpcrt4.dll", CharSet = CharSet.Auto)]
public static extern int RpcMgmtEpEltInqNext(
IntPtr InquiryContext,
out RPC_IF_ID IfId,
out IntPtr Binding,
out Guid ObjectUuid,
out IntPtr Annotation
);
The first parameter must be passed by value.
You'll need to translate the RPC_IF_ID struct. It's quite a simple one.
public struct RPC_IF_ID
{
public Guid Uuid;
public ushort VersMajor;
public ushort VersMinor;
}
The two string parameters you used were just wrong. They lead to the marshaller calling CoTaskMemFree on the returned value for Annotation. You don't want that. You will need to use Marshal.PtrToStringAnsi to read the value.
Don't forget to call RpcBindingFree and RpcStringFree as per the docs.
It's a pointer to an array of LSA_UNICODE_STRING structures. I found some code that does the inverse, i.e., create a LSA_UNICODE_STRING from a C# string. You can see that in the helper code section below.
What I have up to and including the call to LsaEnumerateAccountRights() seems to work just fine. Sensible values are returned for the array pointer and for the count.
I am at a loss as to how to get at those blasted strings. Help please? Pretty please?
UPDATE: nobugz's helper function in his answer below is ALMOST right, you only have to divide the length by UnicodeEncoding.CharSize. Thanks to him, I can now see the FIRST string in the array. See the updates at the end of both code sections below.
Now, how the netherworld do I do pointer arithmetic?
UPDATE 2.5: See answer for the functioning code. I lost the old, "wrong" code.
Found it! In this blog post. Now the amended code below works fully. It's even 64-bit safe!
The main code:
IntPtr sid = IntPtr.Zero;
int sidSize = 0;
StringBuilder domainName = new StringBuilder();
int nameSize = 0;
int accountType = 0;
LookupAccountName("\\\\" + tbHost.Text, tbUsername.Text, sid, ref sidSize,
domainName, ref nameSize, ref accountType);
domainName = new StringBuilder(nameSize);
sid = Marshal.AllocHGlobal(sidSize);
bool result = LookupAccountName("\\\\" + tbHost.Text, tbUsername.Text, sid, ref sidSize,
domainName, ref nameSize, ref accountType);
myResults.Text += String.Format("LookupAccountName(): Result {0}, SID {1}\n", result, sid);
LSA_UNICODE_STRING systemName = string2LSAUS("\\\\" + tbHost.Text);
IntPtr policyHandle = IntPtr.Zero;
LSA_OBJECT_ATTRIBUTES objAttrs = new LSA_OBJECT_ATTRIBUTES();
uint retVal = LsaOpenPolicy(ref systemName, ref objAttrs,
POLICY_LOOKUP_NAMES | POLICY_VIEW_LOCAL_INFORMATION, out policyHandle);
myResults.Text += String.Format("LsaOpenPolicy(): Result {0}, Policy Handle {1}\n", retVal, policyHandle);
IntPtr rightsArray = IntPtr.Zero;
ulong rightsCount = 0;
long lretVal = LsaEnumerateAccountRights(policyHandle, sid, out rightsArray, out rightsCount);
retVal = LsaNtStatusToWinError(lretVal);
if (retVal != 0)
throw new System.ComponentModel.Win32Exception((int)retVal);
myResults.Text += String.Format("LsaEnumerateAccountRights(): Result {0}, RightsArray {1}, Count {2}\n",
retVal, rightsArray, rightsCount);
LSA_UNICODE_STRING myLsaus = new LSA_UNICODE_STRING();
for (ulong i = 0; i < rightsCount; i++)
{
IntPtr itemAddr = new IntPtr(rightsArray.ToInt64() + (long)(i * (ulong) Marshal.SizeOf(myLsaus)));
myLsaus = (WinNetUtils.LSA_UNICODE_STRING)Marshal.PtrToStructure(itemAddr, myLsaus.GetType());
string thisRight = WinNetUtils.LSAUS2string(myLsaus);
NonBlockingPrint(wmiResults, "Right #{0}: {1}\n", i+1, thisRight);
}
LsaClose(policyHandle);
The helper functions, imports etc:
public const int POLICY_VIEW_LOCAL_INFORMATION = 0x1;
public const int POLICY_LOOKUP_NAMES = 0x00000800;
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)]
public static extern UInt32 LsaNtStatusToWinError(
long Status);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true)]
public static extern bool ConvertStringSidToSid(
string StringSid, out IntPtr pSid);
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, SetLastError = true, PreserveSig = true)]
public static extern bool LookupAccountName(
string lpSystemName, string lpAccountName,
IntPtr psid, ref int cbsid,
StringBuilder domainName, ref int cbdomainLength,
ref int use );
[DllImport("advapi32.dll", CharSet = CharSet.Unicode, PreserveSig = true)]
public static extern UInt32 LsaOpenPolicy(
ref LSA_UNICODE_STRING SystemName,
ref LSA_OBJECT_ATTRIBUTES ObjectAttributes,
Int32 DesiredAccess,
out IntPtr PolicyHandle );
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern long LsaEnumerateAccountRights(
IntPtr PolicyHandle, IntPtr AccountSid,
out /* LSA_UNICODE_STRING[] */ IntPtr UserRights,
out ulong CountOfRights);
[DllImport("advapi32.dll", SetLastError = true, PreserveSig = true)]
public static extern long LsaClose(
IntPtr PolicyHandle);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LSA_UNICODE_STRING
{
public UInt16 Length;
public UInt16 MaximumLength;
public IntPtr Buffer;
}
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct LSA_OBJECT_ATTRIBUTES
{
public IntPtr RootDirectory;
public IntPtr SecurityDescriptor;
public IntPtr SecurityQualityOfService;
public LSA_UNICODE_STRING ObjectName;
public UInt32 Attributes;
public UInt32 Length;
}
public static LSA_UNICODE_STRING string2LSAUS(string myString)
{
LSA_UNICODE_STRING retStr = new LSA_UNICODE_STRING();
retStr.Buffer = Marshal.StringToHGlobalUni(myString);
retStr.Length = (UInt16)(myString.Length * UnicodeEncoding.CharSize);
retStr.MaximumLength = (UInt16)((myString.Length + 1) * UnicodeEncoding.CharSize);
return retStr;
}
public static string LSAUS2string(LSA_UNICODE_STRING lsaus)
{
char[] cvt = new char[lsaus.Length / UnicodeEncoding.CharSize];
Marshal.Copy(lsaus.Buffer, cvt, 0, lsaus.Length / UnicodeEncoding.CharSize);
return new string(cvt);
}
This ought to work for you:
private static string LSAUS2String(LSA_UNICODE_STRING lsa) {
char[] cvt = new char[lsa.Length];
Marshal.Copy(lsa.Buffer, cvt, 0, lsa.Length);
return new string(cvt);
}