我有一個服務來將文件從工作文件夾移動到備份文件夾。這些文件夾位於網絡共享上,所以有時我們會使用諸如記事本之類的東西來打開文件來查看它。人們不是(好,不應該)正在編輯,只是看。如何刪除文件鎖
當我們嘗試移動該文件時,我獲得了拒絕權限。我在C#中尋找一種方法來強制刪除文件鎖,以便服務可以將文件移動到備份文件夾。
我有一個服務來將文件從工作文件夾移動到備份文件夾。這些文件夾位於網絡共享上,所以有時我們會使用諸如記事本之類的東西來打開文件來查看它。人們不是(好,不應該)正在編輯,只是看。如何刪除文件鎖
當我們嘗試移動該文件時,我獲得了拒絕權限。我在C#中尋找一種方法來強制刪除文件鎖,以便服務可以將文件移動到備份文件夾。
您必須使用P/Invoke。這些都是你所關心的功能:
[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);
這裏的相似,我已經成功使用一些代碼:
[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
}
}
編輯:由於在下面的意見注意到OP時,編譯爲64位,您需要使用ToInt64而不是ToInt32。更多信息可以在here找到。
這是在Windows上嗎?如果你有關鍵文件,那麼讓它們對其他用戶是隻讀的,否則任何進程都可以鎖定它。 – muratgu
聽起來像你想**複製**他們而不是移動?移動將複製後從源文件夾中刪除文件。 – Slai