2012-08-30 21 views
0

我通過一些P/Invoke拉了一個SafeFileHandle。這裏有一個片段:文件路徑> MAX_PATH並將二進制插入到數據庫

[DllImport("kernel32.dll", SetLastError = true, CharSet = CharSet.Unicode)] 
    internal static extern SafeFileHandle CreateFile(
     string lpFileName, 
     EFileAccess dwDesiredAccess, 
     EFileShare dwShareMode, 
     IntPtr lpSecurityAttributes, 
     ECreationDisposition dwCreationDisposition, 
     EFileAttributes dwFlagsAndAttributes, 
     IntPtr hTemplateFile); 

然後,我可以很容易地握住手柄:

SafeFileHandle fileHandle = CreateFile(path, EFileAccess.GenericRead, EFileShare.None, IntPtr.Zero,ECreationDisposition.OpenExisting, 0, IntPtr.Zero); 

我必須這樣做,因爲System.IO.File只需要一個路徑字符串,我需要支持完全合格的路徑比更大260個字符MAX_PATH

無論如何,我有一個命令過程在sql server上執行插入。我目前將流的字節數組添加到varbinary(max)列(我的大部分文件都小於2MB,因此filestream似乎不值得)。

我目前正在填充命令參數,像這樣:

using (FileStream s = new FileStream(fileHandle, FileAccess.Read)) 
{ 
    byte[] buf = new byte[s.Length]; 
    s.Read(buf, 0, Convert.ToInt32(s.Length)); 
    cmd.Parameters.AddWithValue("@File", buf); 
} 

比平常File.ReadAllBytes,我可以用一個文件路徑小於MAX_PATH使用它只是似乎很慢。有沒有更好的方法把這個二進制數據庫放入數據庫?

回答

1

在dwFlagsAndAttributes中傳遞FILE_FLAG_NO_BUFFERING標誌。由於您一次只能讀取整個文件,因此內置在本機Windows IO中的緩衝是不必要的,並會增加一點開銷。不知道它會爲你節省多少,但有時候每一點點都有幫助。

相關問題