How do I delay a vb.net program until a file opera

2019-07-04 03:09发布

I have this:

    Dim myTemp As String
    myTemp = System.DateTime.Now().ToString("MMMddyyyy_HHmmss") & ".pdf"

    System.IO.File.Copy(myFile, "c:\" & myTemp)
    Application.DoEvents()
    OpenFile(myTemp)

The problem is that when I call OpenFile, which is just a call to a sub that opens a file, it cannot find the file. This is because it is calling it so quickly that the program doesn't have time to actually create the file before the open takes place.

I thought that DoEvents() would rectify this but it does not. I need to wait until the file is created before I open the file. How can I do that?

11条回答
倾城 Initia
2楼-- · 2019-07-04 03:22

First, you should not call DoEvents anywhere. For the most part, when it is used, it is a hack to circumvent what should really be an asynchronous operation.

That being said, the Copy method is a synchronous operation. The call to OpenFile will not occur until the call to Copy completes.

That being said when the call to OpenFile occurs, if the file does not exist, it is because you copied it to the wrong place, or because some other process is working on the file in question.

查看更多
淡お忘
3楼-- · 2019-07-04 03:25

This is a bit hacky, but it should work.

Do Until (System.IO.File.Exists("C:\" & myTemp))
    Threading.Thread.Sleep(1)
Loop
查看更多
迷人小祖宗
4楼-- · 2019-07-04 03:28

In addition to Tom's answer, isnt it better to put a Application.DoEvents() rather then making the thread sleep?

查看更多
你好瞎i
5楼-- · 2019-07-04 03:32

I thinf Synclock is not good for this case

for explaination, MSDN can help me

The SyncLock statement ensures that multiple threads do not execute the same statements at the same time. When the thread reaches the SyncLock block, it evaluates the expression and maintains this exclusivity until it has a lock on the object that is returned by the expression. This prevents an expression from changing values during the running of several threads, which can give unexpected results from your code.

in my opinion, copy is blocking method, so thread waits until copying is done

can`t be problem in another place?

查看更多
祖国的老花朵
6楼-- · 2019-07-04 03:34

System.Threading.Thread.Sleep(1000);

查看更多
在下西门庆
7楼-- · 2019-07-04 03:39
dim SourceFile as string
dim DestinationFile as string

SourceFile = "c:/archivo.txt"
DestinationFile = "c:/destino/archivo.txt"

If System.IO.File.Exists(SourceFile) = True Then

    System.IO.File.Copy(SourceFile, DestinationFile, True)
    'or
    'My.Computer.FileSystem.CopyFile(SourceFile, DestinationFile, FileIO.UIOption.AllDialogs, FileIO.UICancelOption.DoNothing)

    SourceFile = ""
    DestinationFile = ""

else

    MessageBox.Show("the file don't copy!") 

end if 
查看更多
登录 后发表回答