我正在构建一个将文件作为FileStream
提供的应用程序。我需要能够在不锁定源文件的情况下执行此操作,因为文件流可能会被客户端保留一段时间,并且应用程序可能需要对源文件执行后续写操作。
基本上,我正在寻找一种方法来提供文件的独立副本作为文件流而不是源文件本身。
这是我开始的POC:
Friend Sub Main(args As String())
Dim fs = GetServerFile()
Dim t = SomeOperationThatOverwritesServerFile()
'just simulate using the file for some period of time,
'even thought this probably isn't needed bc it's already locked anyway.
For i = 1 To 10
fs.Seek(0, SeekOrigin.Begin)
Threading.Thread.Sleep(1000)
Next
fs.Close()
End Sub
Friend Function GetServerFile() As FileStream
GetServerFile = File.OpenRead(serverFilePath)
End Function
Friend Async Function SomeOperationThatOverwritesServerFile() As Task
'just simulate something that overwrites the server file with fresh data.
For i = 1 To 5
Await Task.Run(Sub() File.Copy(newSourceFilePath, serverFilePath, True))
Await Task.Delay(2000)
Next
End Function
此代码在IOException
上抛出Await Task.Run(Sub() File.Copy(newSourceFilePath, serverFilePath, True))
,因为该文件已被客户端锁定。很公平。
现在我正在查看FileStream.CopyTo()
方法,但是,我不确定任何FileStream
构造函数重载是否有效:
Friend Function GetServerFile() As FileStream
GetServerFile = File.OpenRead(serverFilePath).CopyTo(New FileStream(WHICH OVERLOAD DO I USE?))
End Function
他们都会String
路径指向文件或SafeFileHandle
。
非常感谢任何指导。
答案 0 :(得分:0)
CopyTo
方法需要FileStream
,而实际上它需要Stream
(这是有道理的,因为CopyTo
定义了Stream
,而不是FileStream
{1}}),所以我可以像这样使用MemoryStream
:
Friend Function GetServerFile() As MemoryStream
GetServerFile = New MemoryStream()
Using inputStream = File.OpenRead(serverFilePath)
inputStream.CopyTo(GetServerFile)
End Using
End Function