如果您将DirectoryInfo实例从PC1发送到PC2,GetFiles或GetDirectories是否还在工作?
public void DirTest()
{
//On first PC:
DirectoryInfo driveC = new DirectoryInfo(@"C:\randomdir\");
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ns = new MemoryStream();
bf.Serialize(ns, driveC);
SendStream(ns); //Sending the stream to the second PC
//On second PC:
ns = ReceiveStream(); //Receiving the stream from the first PC
ns.Position = 0;
DirectoryInfo di = (DirectoryInfo)bf.Deserialize(ns);
//Does this work?
foreach (FileInfo item in di.GetFiles())
{
Debug.WriteLine(item);
}
}
如果您在同一台PC上执行该代码,它可以工作,但我没有环境来测试它是否适用于2个不同的PC。
答案 0 :(得分:4)
嗯,只有在两台计算机上都有相同的目录名时才能使用它。我们来看看reference source ...
首先,DirectoryInfo
继承FileSystemInfo
,因此当您反序列化DirectoryInfo
时,会调用此构造函数:
[System.Security.SecurityCritical] // auto-generated
private DirectoryInfo(SerializationInfo info, StreamingContext context) : base(info, context)
{
Directory.CheckPermissions(string.Empty, FullPath, checkHost: false);
DisplayPath = GetDisplayName(OriginalPath, FullPath);
}
其中base
是FileSystemInfo
,并使用此构造函数:
[ResourceExposure(ResourceScope.None)]
[ResourceConsumption(ResourceScope.Machine, ResourceScope.Machine)]
protected FileSystemInfo(SerializationInfo info, StreamingContext context)
{
if (info == null)
throw new ArgumentNullException("info");
Contract.EndContractBlock();
// Must use V1 field names here, since V1 didn't implement
// ISerializable.
FullPath = Path.GetFullPathInternal(info.GetString("FullPath"));
OriginalPath = info.GetString("OriginalPath");
// Lazily initialize the file attributes.
_dataInitialised = -1;
}
因此,您可以看到序列化的唯一内容是FullPath
和OriginalPath
值。目录中的数据未被序列化,如果您调用DirectoryInfo.GetFiles()
,您将枚举本地计算机中的文件,而不是首先序列化DirectoryInfo
的计算机。实际上,源代码专门说Lazily initialize the file attributes
,这意味着它们在被请求时被加载。
// Returns an array of Files in the DirectoryInfo specified by path
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
public FileInfo[] GetFiles()
{
return InternalGetFiles("*", SearchOption.TopDirectoryOnly);
}
哪个电话:
// Returns an array of Files in the current DirectoryInfo matching the
// given search criteria (ie, "*.txt").
[ResourceExposure(ResourceScope.Machine)]
[ResourceConsumption(ResourceScope.Machine)]
private FileInfo[] InternalGetFiles(String searchPattern, SearchOption searchOption)
{
Contract.Requires(searchPattern != null);
Contract.Requires(searchOption == SearchOption.AllDirectories || searchOption == SearchOption.TopDirectoryOnly);
IEnumerable<FileInfo> enble = FileSystemEnumerableFactory.CreateFileInfoIterator(FullPath, OriginalPath, searchPattern, searchOption);
List<FileInfo> fileList = new List<FileInfo>(enble);
return fileList.ToArray();
}
再一次,您看到序列化信息中没有使用任何内容。