内存映射文件:无法找到路径的一部分

3

我有几种使用MemoryMappedFiles写入/读取数据的方法。如果我使用简单的字符串文件名,例如“file.mmf”,它们可以正常运行。但是,如果我使用完整的目录路径,则会抛出上述异常 - Exception has been thrown by the target of an invocation. 其中包含内部异常 - {"Could not find a part of the path."}。下面是我的方法示例:

public void WriteToFile(string fileName, string value)
{
    string newFileName = CombineDirectory(fileName);
    byte[] newValue = Encoding.UTF8.GetBytes(value);
    long capacity = newValue.Length + INT_MAXVALUE_TO_BYTEARRAY_LENGTH;

    using (var mmf = MemoryMappedFile.CreateFromFile(newFileName, FileMode.Create, newFileName, capacity))
    {
        using (var accesor = mmf.CreateViewAccessor())
        {
            byte[] newValueLength = BitConverter.GetBytes(value.Length);
            accesor.WriteArray(0, newValueLength, 0, newValueLength.Length);
            accesor.WriteArray(INT_MAXVALUE_TO_BYTEARRAY_LENGTH, newValue, 0, newValue.Length);
        }
    }
}

我的路径看起来像这样:
"C:\\Users\\MyUser\\Documents\\Visual Studio 2012.mmf"

我正在使用

Path.Combine

异常发生在第一个 'using' 行上。如果我尝试使用相同的文件路径创建文件,则会出现异常。
File.Create

文件已经成功创建。
如果有任何建议,将不胜感激。
敬礼。
1个回答

5

您需要确保mapName参数(即调用CreateFromFile时的第三个参数)与文件路径不相同。如果相同,它将抛出PathNotFound异常。我同意这并不能帮助你找出它为什么失败。

因此,您可以选择以下几种地图名称值:

  • 生成一些唯一键,例如Guid.NewGuid().ToString()
  • 使用一个常量值,例如"MySpecialMapForThings"
  • 使用某些约定,例如生成一个唯一键,您还将其用于映射文件的文件名部分。

以下是最后一种选项的示例:

public static Tuple<FileInfo, string> GenerateMapInfo(string mapDirectory, string fileExtension)
{
    var uniqueMapName = Guid.NewGuid().ToString();
    var fileName = Path.Combine(mapDirectory, Path.ChangeExtension(uniqueMapName, fileExtension));
    return Tuple.Create(new FileInfo(fileName), uniqueMapName);
}

public void WriteToFile(Tuple<FileInfo, string> mapInfo, string value)
{
    byte[] newValue = Encoding.UTF8.GetBytes(value);
    long capacity = newValue.Length + INT_MAXVALUE_TO_BYTEARRAY_LENGTH;

    using (var mmf = MemoryMappedFile.CreateFromFile(mapInfo.Item1.FullName, FileMode.Create, mapInfo.Item2, capacity))
    using (var accesor = mmf.CreateViewAccessor())
    {
        byte[] newValueLength = BitConverter.GetBytes(value.Length);
        accesor.WriteArray(0, newValueLength, 0, newValueLength.Length);
        accesor.WriteArray(INT_MAXVALUE_TO_BYTEARRAY_LENGTH, newValue, 0, newValue.Length);
    }
}

起初,我的mapName只是文件名(不包括路径),这也没有起作用。然而,使用GUID使得这个问题得到了解决。感谢你的帮助。 - Georgi-it
@Georgi-it 如果你从文件名中删除扩展名并将其用作地图名称,它就会起作用(当然,这需要你的文件名有一个扩展名)。 - Alex
有没有任何文档说明地图名称必须与文件路径不同?无论在哪里? - antlersoft

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接