簡體   English   中英

嘗試使用C#打開PowerPoint文件時引發異常

[英]Exception thrown when trying to open a PowerPoint file with C#

我正在開發我的第一個C#應用程序。 我正在嘗試以全屏模式打開PowerPoint文件。 該代碼需要cmd參數。 我將powerpoint test.pptm放置在與應用程序輸出(調試和發布)相同的文件夾中。 我寫了以下代碼:

        ProcessStartInfo startInfo = new ProcessStartInfo();
        startInfo.CreateNoWindow = false;
        startInfo.UseShellExecute = false;
        startInfo.FileName = "powerpnt.exe";
        startInfo.WindowStyle = ProcessWindowStyle.Hidden;
        startInfo.Arguments = "/s test.pptm";

        try
        {
            using (Process exeProcess = Process.Start(startInfo))
            {
                exeProcess.WaitForExit();
            }
        }
        catch
        {
        }

代碼會編譯,但是當我嘗試通過按鈕運行此代碼時,控制台會指出:

Exception thrown: 'System.ComponentModel.Win32Exception' in System.dll

我嘗試通過更改以下行直接引用pptm文件:

startInfo.Arguments = "/sc:\\path\\to\\full\\file\\test.pptm";

我收到一條錯誤消息,指出Unrecognized escape sequence 有誰之前經歷過這個嗎? 我已經堅持了一段時間。 謝謝!

在文件路徑前面加上@符號

startInfo.Arguments = @"/s c:\path\to\full\file\test.pptm";

從MSDN

逐字字符串文字包含一個@字符,后跟一個雙引號字符,零個或多個字符以及一個結束的雙引號字符。 一個簡單的例子是@“ hello”。 在逐字字符串文字中,定界符之間的字符逐字解釋,唯一的例外是引號-轉義序列。

https://msdn.microsoft.com/en-us/library/aa691090(v=vs.71).aspx

有關使代碼正常工作的一些提示

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.CreateNoWindow = false;            
startInfo.FileName = "powerpnt.exe";
startInfo.WindowStyle = ProcessWindowStyle.Hidden;
startInfo.Arguments = @"/s ""fullpath with spaces in file names""";
  1. 請注意全路徑之前和之后的轉義雙引號。 這是為了在文件名或目錄中容納空格
  2. 刪除行startInfo.UseShellExecute = false

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM