从Powershell写入文件,然后从C#中读取文件

问题描述:

我正在从C#调用Powershell来收集一些信息并使用Out-File将其发送到文本文件。然后我需要读取上述文件中的行,并使用C#中的数据进行操作。从Powershell写入文件,然后从C#中读取文件

string MyCommand = "-Command &{ get-process | Out-File C:\\MyFile.txt}"; 

ProcessStartInfo MyProcInfo = new ProcessStartInfo(); 
MyProcInfo.FileName = "powershell.exe"; 
MyProcInfo.Arguments = MyCommand; 

Process MyProcess = new Process(); 
MyProcess.StartInfo = MyProcInfo; 
MyProcess.Start(); 
MyProcess.WaitForExit(); 

try 
{ 
    var lines = File.ReadLines(@"C:\MyFile.txt"); 
    (etc) 
} 
catch (Exception Ex) 
{ 
    MessageBox.Show(Ex.ToString()); 
} 

因此,当它试图打开文本文件,我得到一个

“找不到文件”

例外。每次都会写入文件IS,所以我假设有一个计时事件正在进行,这就是为什么我使用WaitForExit。但它仍然无法'找到'文件。

+1

你确定你要'C写访问:'和文件写?由于直接写入'C:'时引发的'UnauthorizedAccessException',我对此表示怀疑。使用'MyProcInfo.UseShellExecute = false; MyProcInfo.RedirectStandardOutput = true;',然后将该输出重定向到'string'并查看问题出在哪里。包含'MyProcess.StandardOutput.ReadLine();'的while(!MyProcess.StandardOutput.EndOfStream)'应该有效。 – jAC

+0

请注意:Powershell方面正在工作。该文件确实被写入......我实际上每次都要手动删除它来测试。所以我有写入权限到C:\。当我到达File.ReadLines时遇到问题。那是当我得到文件没有找到 – PSNewb

+0

@wOxxOm如果你不打算做替换,你应该实际使用单引号字符串文字。 – TheIncorrigible1

为什么不用C#而不是用PowerShell编写文件?

您可以利用Diagnostics.Process .NET类(这里是一个PowerShell的例子)

$proc = [Diagnostics.Process]::Start($exe, $arguments) 
$proc.WaitForExit() 
+0

还有比我在这里列出的powershell行更多的东西。为简洁起见,我将其截断。但是它每次运行都会被正确写入。 – PSNewb

+1

您可以直接调用powershell inproc并直接使用输出,而无需将其写入文件系统并再次读取。 查看“https://stackoverflow.com/questions/16398171/powershell-command-through-c-sharp-code”例如 –

我不能告诉你什么是错的,但我可以给你一些提示,故障排除。

  1. MyProcess.WaitForExit后() 添加一个用于测试的文件是否存在。

    if (File.Exists(@"C:\Myfile.txt")) 
    { 
        ... file process code here.... 
    } 
    
  2. 摆脱硬编码的文件名并改用变量。

    string filename = @“C:\ MyFile.txt”;

    串mycommand的= “-Command & {获取过程|出文件” & &名 “}”;

然后当你要访问的文件,请使用:

if (File.Exists(filename)) 
{ 
    ...process the file. 
} 

这样做的好处是,你是100%保证您使用的正是在所有地方相同的文件名。

  1. 在MyProcess.WaitForExit()后添加一个断点。 然后,当执行停止时,导航到该文件,并确保它在那个时间出现,并确保它未被程序锁定。例如,尝试重命名或删除它。如果它仍然被锁定,你不应该能够做这两件事中的任何一件。此外,大多数当前版本的Windows都有可以检查打开文件的位置。如果您告诉我您正在运行的操作系统,我可能会告诉您如何检查该操作系统。

还有一件事:另一张海报提到Windows重定向。我个人从来没有发生这种情况,当文件明确完全合格。

HTH, 约翰

您好!

你可以尝试做这样的事情:

也许它帮助你

namespace ConsoleApplication1 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 

string MyCommand = "-Command &{ if (!(Test-Path 'c:\\test')) {md 'c:\\test'; get-process | Out-File c:\\test\\MyFile.txt}}"; 

ProcessStartInfo MyProcInfo = new ProcessStartInfo(); 
MyProcInfo.FileName = "powershell.exe"; 
MyProcInfo.Arguments = MyCommand; 

Process MyProcess = new Process(); 
MyProcess.StartInfo = MyProcInfo; 
MyProcess.Start(); 
MyProcess.WaitForExit(); 

try 
{ 
    var lines = File.ReadLines(@"c:\test\MyFile.txt"); 
foreach (var ln in lines) { 
    Console.WriteLine(ln); 
    Console.ReadKey(); 

} 
} 
catch (Exception Ex) 
{ 
    Console.WriteLine(Ex.ToString()); 
    Console.ReadKey(); 
} 
     }