문제

기본 응용 프로그램과 완전히 독립적 인 업데이트 프로그램이 있습니다. app.exe를 업데이트하려면 update.exe를 실행합니다. 파일이 사용 중인지 확인하려면 다른 파일로 이동하고 사용중인 경우 오류를 포착합니다. 문제가 발생하지 않으면 다시 이름을 바꿉니다. 적어도 그것은 내 계획이었다 ...

주요 프로그램 : app.exe
업데이트 프로그램 : Update.exe

이 프로그램은 서비스를 실행하지 않고 네트워크를 통해 사용됩니다. 따라서 사용자는 말 그대로 기계의 네트워크를 통해 Exe를 실행하고 있습니다.

update.exe가 실행되면 app.exe를 업데이트해야합니다. app.exe가 아직 사용 중인지 확인하려면 시도/캐치로 다음을 래핑하여 실패했는지 확인했습니다.

io.file.move (upddir & " app.exe", upddir & " app.exe.tst")
io.file.move (upddir & " app.exe.tst", upddir & " app.exe")

재미있는 점은 app.exe가 실행중인 경우에도 이동이 오류없이 app.exe.tst로 이름을 바꿀 수 있다는 것입니다. 오류없이 응용 프로그램을 계속할 수도 있습니다.

나는 내가 마음에서 벗어 났다고 생각했기 때문에 다른 프로그래머가 이것을 보았고 그는 내가 위에서 말한 것을 확인했다.

그래서 우리는 이것을 시도 캐치로 시도했습니다.

dim readfile은 새로운 fileStream (upddir & " app.exe", filemode.open, fileaccess.read, fileshare.none)으로
readfile.dispose ()

나는 파일에 누군가가 있다는 것을 보여줄 것이라고 생각한 Fileshare를 아무것도하지 않았다.

여전히 오류없이 계속되었습니다.

누구든지 내가 사용중인 파일의 이름을 바꿀 수있는 이유를 아는 사람이 있습니까? 또한, 내가 지금하고있는 것보다 더 좋은 방법이 있습니까?

감사! Eroc

도움이 되었습니까?

해결책

응용 프로그램에 다른 인스턴스가 실행되는지 확인하기 위해 다음을 수행 할 수 있습니다.

Process.GetProcessesByName("app.exe", "Machine1").Length > 0

이는 앱이 실행 중인지 확인하는보다 적절한 방법입니다.

살펴보십시오 file.move MSDN 문서. 그것은 예외가 발생하는 것을 자세히 설명합니다. Vista에서 사용중인 경우에도 EXE의 이름을 바꿀 수 있습니다.

다른 팁

"사용"을 사용한 동일한 코드 :)

Public Function FileInUse(ByVal sFile As String) As Boolean
 Dim thisFileInUse As Boolean = False
 If System.IO.File.Exists(sFile) Then
     Try
       Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                ' thisFileInUse = False
       End Using
     Catch
       thisFileInUse = True
     End Try
 End If
 Return thisFileInUse
End Function

당신이 할 수있는 일은 대상 응용 프로그램을 관리인 EXE로 바꾸는 것입니다.

이 관리인은 대상 응용 프로그램을 생성하지만 공유 위치에 잠긴 파일도 생성합니다. 앱이 종료되면 잠금이 해제되고 파일이 삭제됩니다.

그런 다음 app.exe를 업데이트하기 전에 공유 위치에 잠긴 파일이 있는지 확인합니다. 잠금 파일이 있으면 App.exe가 사용 중입니다.

관리자 프로그램은 창이없는 응용 프로그램 일 수 있습니다. 다음 콘솔 앱은해야 할 일을 거의합니다.

class Program
{
    static string lockFileName;
    static System.IO.StreamWriter lockFileWrtier;
    static void Main(string[] args)
    {
        lockFileName = "AppLock_" + System.IO.Path.GetRandomFileName();

        lockFileWrtier = new System.IO.StreamWriter(lockFileName);

        System.Diagnostics.Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.EnableRaisingEvents = true;
        p.Exited += new EventHandler(p_Exited);

        p.Start();

        Console.WriteLine("Press any key to stop");
        Console.ReadKey();
    }

    static void p_Exited(object sender, EventArgs e)
    {
        lockFileWrtier.Dispose();
        System.IO.File.Delete(lockFileName);

        Console.WriteLine("Process has exited");
    }
}

그런 다음 업데이터는 모든 "Applock_*"파일을 찾고 있으며, 그 중 하나에 쓰기 잠금을 얻을 수 없다면 Write Lock으로 열려고 시도합니다. EXE가 사용 중입니다.

도움이 되었기를 바랍니다.

이것이 내가 한 일입니다. 네트워크 스캔은 피어 투 피어 네트워크에서 작동하지 않았습니다. 다른 컴퓨터를 전혀 해결하지 못했습니다.

어쨌든 여기에 있습니다.

Private Sub Checkfileiffileisinuse (byval thefilename as string)
노력하다
'Vista OS에서 사용중인 파일의 이름을 바꿀 수 있습니다.
원본 파일의 '사용중인'은 새 파일 이름을 따릅니다.

      Dim testfile As String = thefilename & ".tst"<br />

      If IO.File.Exists(testfile) Then<br />
          IO.File.Delete(testfile)<br />
      End If<br />

      ' so we have to rename it to something else<br />
      IO.File.Move(thefilename, testfile)<br />

      ' copy it back to the original file name in case something <br />breaks 
      ' this just keeps them in working order if it does<br />
      IO.File.Copy(testfile, thefilename)<br />

      ' then we try to delete the original file that could be in use <br />
      ' which will return an 'in use' error at this point<br />
      If IO.File.Exists(testfile) Then<br />
          IO.File.Delete(testfile)<br />
      End If<br />

  Catch ex As Exception<br />
      'throw it to the originating method<br />
      Throw<br />
  End Try<br />

종료 서브

이것이 다음 사람에게 도움이되기를 바랍니다.

Public Function FileInUse(ByVal sFile As String) As Boolean
    If System.IO.File.Exists(sFile) Then
        Try
            Dim F As Short = FreeFile()
            FileOpen(F, sFile, OpenMode.Binary, OpenAccess.ReadWrite, OpenShare.LockReadWrite)
            FileClose(F)
        Catch
            Return True
        End Try
    End If
End Function
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top