【问题标题】:C# assigning value to variable says it cannot find the file?C#为变量赋值说它找不到文件?
【发布时间】:2016-04-06 10:31:44
【问题描述】:

我有一个运行批处理文件的非常简单的方法。方法是这样的:

private  string _binnPath = Application.StartupPath + "\\Binn";

public void DumpFileSystem(string snapshotFolder)
{
    var cwd = Directory.GetCurrentDirectory();
    Directory.SetCurrentDirectory(_binnPath);

    var snapshotOutput = Path.Combine(Application.StartupPath, snapshotFolder);
    snapshotOutput = Path.Combine(snapshotOutput, DateTime.UtcNow.Ticks + "-files.txt");

    var batCommand = _binnPath + "\\DumpFileSystem.bat";
    string batFilename = batCommand + " " + snapshotOutput;

    using (var process = Process.Start(batFilename))
    {
        process?.WaitForExit();
    }

    Directory.SetCurrentDirectory(cwd);
}

批处理文件是这样的:

dir /s c:\ >  %1

在线var batCommand = _binnPath + "\\DumpFileSystem.bat";我收到这个:

“System.ComponentModel.Win32Exception”类型的未处理异常 发生在 System.dll 中

附加信息:系统找不到指定的文件

这根本没有意义,因为我只是分配一个变量。 我要做的就是使用 snapshotOutput 变量运行批处理文件。 这应该没那么难。

问题

  1. 知道如何运行批处理文件吗?和

  2. 为什么变量的设置甚至不应该在寻找文件时抛出错误?

【问题讨论】:

  • 在 Process.Start(batFilename) 上放一个断点,调试并停在那里,查看 batFilename 的值并检查文件是否在您期望的位置。变化是文件不在%APPROOT%/bin/debug/Binn文件夹中
  • 我认为这可能是因为您尝试将参数传递到应该是路径的地方。
  • 为什么要调用SetCurrentDirectory函数?您是否尝试注释掉该行?

标签: c# batch-file process


【解决方案1】:

删除这些代码

string batFilename = batCommand + " " + snapshotOutput;

你必须改变进程开始

Process.Start(new ProcessStartInfo(batCommand , snapshotOutput))

【讨论】:

  • 直截了当。甚至比我自己的答案更喜欢它。
  • 好吧,这行得通——但为什么呢?你说我应该删除的那一行只是一个变量赋值。发生错误时,我还没有开始运行进程。
  • @Toxantron 说得对:“这是 Visual Studio 中的一种视错觉,通常由旧文件或代码优化引起。”错误在“Process.Start”中,但 Visual Studio 在上排抛出异常。我建议在 Process.Start 之前的行上发出一个 Console.Writeline,它将在两个版本中执行...
【解决方案2】:
  1. 您应该只明确传递批处理的路径和参数。否则 windows 会尝试将参数合并到不存在的路径中。
  2. 这是 Visual Studio 中的一种视觉错觉,通常由旧文件或代码优化引起。

请看这里: https://stackoverflow.com/a/5766669/6082960

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2020-07-23
    • 2018-05-25
    相关资源
    最近更新 更多