我正在尝试编写一个简单的程序,该程序将采用由两列组成的 CSV,并从第一列中给定一个关键字,从第二列返回相应的值。问题是我需要 CSV 位于备用数据流中,以使程序尽可能可移植(我想这样做,以便当用户将 CSV 文件放在可执行文件上时,CSV 被覆盖)。这就是我尝试使用 WinAPI 的 CreateFile 函数的原因——.NET 不支持备用数据流。不幸的是,我失败得很惨。
在当前状态下,程序应该读取名为 test.csv 的文件。我想对其执行 CreateFile,将 intPtr 句柄转换为 SafeFileHandle,然后将 SafeFileHandle 传递给 FileStream 构造函数。不过,我所能达到的最好成绩是一条空流。在我看来,该程序实际上并没有获得正确的句柄。当我尝试“CREATE_ALWAYS”或“CREATE_NEW”而不是“OPEN_ALWAYS”时,无论我如何处理其余参数,我都会收到“无效句柄”错误。使用“OPEN_ALWAYS”时,当我检查“stream.Name”的值时,我得到“Unknown”。
代码如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Runtime.InteropServices;
using Microsoft.Win32.SafeHandles;
namespace Searcher
{
public partial class Searcher : Form
{
public static List<string> keywords;
public static List<string> values;
public Searcher()
{
InitializeComponent();
//byte[] path = Encoding.UTF8.GetBytes("C:\\Users\\as\\Documents\\test.csv");
SafeFileHandle safeADSHandle = NativeMethods.CreateFileW("test.csv",
NativeConstants.GENERIC_READ,
NativeConstants.FILE_SHARE_READ,
IntPtr.Zero,
NativeConstants.OPEN_ALWAYS,
0,
IntPtr.Zero);
//var safeADSHandle = new SafeFileHandle(handle, true);
if (safeADSHandle.IsInvalid)
{
Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error());
}
var stream = new FileStream(safeADSHandle, FileAccess.Read);
MessageBox.Show(stream.Name);
var reader = new StreamReader(stream);
Searcher.keywords = new List<string>();
Searcher.values = new List<string>();
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
var values = line.Split(',');
Searcher.keywords.Add(values[0]);
Searcher.values.Add(values[1]);
}
cbKeyword.DataSource = Searcher.keywords;
cbKeyword.AutoCompleteSource = AutoCompleteSource.ListItems;
}
private void btnSearch_Click(object sender, EventArgs e)
{
tbResult.Text = Searcher.values[cbKeyword.SelectedIndex];
}
}
}
public partial class NativeMethods
{
[DllImportAttribute("kernel32.dll", SetLastError = true, EntryPoint = "CreateFile")]
public static extern SafeFileHandle CreateFileW(
[InAttribute()] [MarshalAsAttribute(UnmanagedType.LPWStr)] string lpFileName,
uint dwDesiredAccess,
uint dwShareMode,
[InAttribute()] System.IntPtr lpSecurityAttributes,
uint dwCreationDisposition,
uint dwFlagsAndAttributes,
[InAttribute()] System.IntPtr hTemplateFile
);
}
public partial class NativeConstants
{
/// GENERIC_WRITE -> (0x40000000L)
public const int GENERIC_WRITE = 1073741824;
public const uint GENERIC_READ = 2147483648;
/// FILE_SHARE_DELETE -> 0x00000004
public const int FILE_SHARE_DELETE = 4;
/// FILE_SHARE_WRITE -> 0x00000002
public const int FILE_SHARE_WRITE = 2;
/// FILE_SHARE_READ -> 0x00000001
public const int FILE_SHARE_READ = 1;
/// OPEN_ALWAYS -> 4
public const int OPEN_ALWAYS = 4;
public const int CREATE_NEW = 1;
}
编辑 我对上面的代码稍作改动,以反射(reflect)注释后的变化。现在我不从 IntPtr 转换为 SafeFileHandle。可能要提到的一件事是,在进行此更改之前,我尝试读取 handle.ToString() 的值以查看它是否正在更改,而它确实是 -- 它是一个随机数。
请您参考如下方法:
这不起作用的原因是因为您指定了一个没有字符集的入口点。当你在DllImport中没有指定字符集时,默认是CharSet.Ansi,这意味着平台调用将搜索函数如下:
- 首先用于未损坏的导出函数,即来自您指定的入口点的名称
CreateFile(kernel32.dll中不存在) - 接下来,如果未找到未混淆的名称,它将根据字符集搜索已混淆的名称,因此它将搜索
CreateFileA
因此它将找到 CreateFileA 导出函数,该函数假定传递给它的任何字符串都是 1 字节字符 ANSI 格式。但是,您将字符串编码为宽字符串。请注意,函数的宽字符版本称为 CreateFileW(函数的 ANSI 版本和宽字符版本之间的这种区别在 Windows API 中很常见)。
要解决此问题,您只需确保参数的编码与您导入的函数所期望的相匹配。因此,您可以删除 EntryPoint 字段,在这种情况下,它将使用 C# 方法名称来查找导出的函数(因此它将找到 CreateFileW)。
但是为了让它更清楚,我会编写您的平台调用代码如下:
[DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
public static extern IntPtr CreateFile(
[MarshalAs(UnmanagedType.LPTStr)] string filename,
[MarshalAs(UnmanagedType.U4)] FileAccess access,
[MarshalAs(UnmanagedType.U4)] FileShare share,
IntPtr securityAttributes,
[MarshalAs(UnmanagedType.U4)] FileMode creationDisposition,
[MarshalAs(UnmanagedType.U4)] FileAttributes flagsAndAttributes,
IntPtr templateFile);
我从 pinvoke.net 中获取了这个网站,它应该是您编写 pinvoke 代码的首选,而不是尝试自己编写代码(尤其是如果您不熟悉 Windows API 或编码 :)。
没有错误的原因可能是 CreateFile 正在创建文件,因为它无法找到它。
不过文件名将显示为“[Unknown]”。我怀疑这是因为从句柄获取文件名的代码非常重要。
