Domanda

Ho un programma di utilità che ho scritto in VB.net che viene eseguito come attività pianificate. Si chiede internamente altro eseguibile e deve accedere a un'unità mappata. A quanto pare Windows ha problemi con le operazioni pianificate di accesso a unità mappate quando l'utente non è connesso, anche quando le credenziali di autenticazione sono forniti al compito in sé. Ok, va bene.

Per ovviare a questo ho appena passato la mia domanda il percorso UNC.

process.StartInfo.FileName = 'name of executable'
process.StartInfo.WorkingDirectory = '\\unc path\'
process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
process.StartInfo.Arguments = 'arguments to executable'
process.Start()

Questa è la stessa implementazione ho usato con l'unità mappata, ma utilizzando il percorso UNC, il processo non si comporta come se il percorso UNC è la directory di lavoro.

Ci sono problemi noti di impostazione ProcessStartInfo.WorkingDirectory a un percorso UNC? Se no, che cosa sto sbagliando?

È stato utile?

Soluzione

Il tuo problema con le unità mappate quando gli utenti non sono connessi in è che non esistono. Azionamenti sono solo mappati e disposizione del utente attualmente connesso. Se nessuno è connesso, nessuna unità sono mappate.

Per risolvere il problema è possibile eseguire attraverso CMD, PUSHD chiamata che sarà mappare l'UNC a un'unità di dietro le quinte e quindi eseguire il codice. Ho copiato il file tree.com dal mio system32 e messo sul mio file server come "tree4.com" e questo codice funziona come previsto (sto anche reindirizzando standard output in modo da poter vedere i risultati della chiamata, ma che è non necessario)

Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click

    Using P As New Process()
        'Launch a standard hidden command window
        P.StartInfo.FileName = "cmd.exe"
        P.StartInfo.WindowStyle = ProcessWindowStyle.Hidden
        P.StartInfo.CreateNoWindow = True

        'Needed to redirect standard error/output/input
        P.StartInfo.UseShellExecute = False

        P.StartInfo.RedirectStandardInput = True
        P.StartInfo.RedirectStandardOutput = True

        'Add handler for when data is received
        AddHandler P.OutputDataReceived, AddressOf SDR

        'Start the process
        P.Start()

        'Begin async data reading
        P.BeginOutputReadLine()

        '"Map" our drive
        P.StandardInput.WriteLine("pushd \\file-server\File-Server")

        'Call our command, you could pass args here if you wanted
        P.StandardInput.WriteLine("tree2.com  c:\3ea7025b247d0dfb7731a50bf2632f")

        'Once our command is done CMD.EXE will still be sitting around so manually exit
        P.StandardInput.WriteLine("exit")
        P.WaitForExit()
    End Using

    Me.Close()
End Sub
Private Sub SDR(ByVal sender As Object, ByVal e As DataReceivedEventArgs)
    Trace.WriteLine(e.Data)
End Sub

Altri suggerimenti

mi sono imbattuto in questo problema e la soluzione accettata è un po 'complicato per me. Quello che ho fatto è stato quello di prendere il percorso UNC e copiare il contenuto di esso per [Path.GetTempDir()]\[Guid.NewGuid().ToString()] e quindi utilizzare tale come la mia directory di lavoro del process.StartInfo.WorkingDirectory. Avvolgere questa funzionalità in una classe denominata "Ambiente" che attuerà IDisposable e nel dispose ripulire la directory temp si è creato. Qualcosa di simile (ignorare i riferimenti Impostazioni):

 using (var env = new ProcessEnvironment(settings))
                {
                    filePath = Path.Combine(env.WorkingDirectory, settings.ApplicationEXE);
                    var psi = new ProcessStartInfo
                    {
                        UseShellExecute = false,
                        FileName = filePath,
                        WorkingDirectory = env.WorkingDirectory,
                        Arguments = (args != null && args.Length > 0 ? String.Join(" ", args) : null)
                    };

                    var proc = Process.Start(psi);

                    if (env.ExecutingFromTempDir || settings.WaitForExit)
                        proc.WaitForExit();
                }

e si presenta come ProcessEnvironment:

 class ProcessEnvironment : IDisposable
    {
        private Settings itsSettings;
        private string itsTempDestDirectory;
        public string WorkingDirectory { get; set; }
        public bool ExecutingFromTempDir { get { return !String.IsNullOrEmpty(itsTempDestDirectory); } }

        public ProcessEnvironment(Settings settings)
        {
            this.itsSettings = settings;

            WorkingDirectory = GetWorkingDirectory();
        }

        private string GetWorkingDirectory()
        {
            var dirInfo = new DirectoryInfo(itsSettings.StartupFolder);

            if (!IsUncDrive(dirInfo))
                return itsSettings.StartupFolder;

            return CreateWorkingDirectory(dirInfo);
        }

        private string CreateWorkingDirectory(DirectoryInfo dirInfo)
        {
            var srcPath = dirInfo.FullName;
            itsTempDestDirectory = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            Directory.CreateDirectory(itsTempDestDirectory);

            //Now Create all of the directories
            foreach (string dirPath in Directory.GetDirectories(srcPath, "*", SearchOption.AllDirectories))
                Directory.CreateDirectory(dirPath.Replace(srcPath, itsTempDestDirectory));

            //Copy all the files & Replaces any files with the same name
            foreach (string newPath in Directory.GetFiles(srcPath, "*.*", SearchOption.AllDirectories))
                File.Copy(newPath, newPath.Replace(srcPath, itsTempDestDirectory), true);

            return itsTempDestDirectory;
        }

        private bool IsUncDrive(DirectoryInfo dirInfo)
        {
            Uri uri = null;
            if (!Uri.TryCreate(dirInfo.FullName, UriKind.Absolute, out uri))
            {
                return false;
            }
            return uri.IsUnc;
        }



        public void Dispose()
        {
            try
            {
                if (ExecutingFromTempDir)
                    Directory.Delete(itsTempDestDirectory, true);

            }
            catch (Exception ex)
            {  //do nothing - if we can't delete then we can't do it
                Console.WriteLine("Failed in Dispose: " + ex);
            }
        }
    }
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top