在 C# 中使用 OpenFIleDialog 获取 word 文档的路径

Using OpenFIleDialog to get path for word document in C#

我正在尝试使用 OpendFileDialog 获取要传递给 word 应用程序实例的路径。到目前为止,这是我的代码。它告诉我‘抱歉,我们找不到您的文件。是否已移动、重命名或删除?

这是我的代码。谢谢

OpenFileDialog OpenFileDialog1 = new OpenFileDialog();

    private void button1_Click(object sender, EventArgs e)
    {
        OpenFileDialog1.Filter = @"All Files|*.*";

        if (openFile.ShowDialog() == DialogResult.OK)
        {
            string filePath = System.IO.Path.GetFullPath(OpenFileDialog1.FileName);
        }

        Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
        Microsoft.Office.Interop.Word.Document wordDoc = null;       

        object fileName = "filePath";

        object missing = System.Type.Missing;
        document = App.Documents.Open(ref fileName, ref missing, ref missing, ref missing, 
                                  ref missing, ref missing, ref missing, ref missing, 
                                  ref missing, ref missing, ref missing, ref missing,
                                  ref missing, ref missing, ref missing, ref missing);

您当前将 fileName 设置为 "filePath" 作为字符串而不是实际路径。您会注意到在您的代码中,您正在 if 范围内设置 filePath 变量,该范围仅适用于 if 语句。

OpenFileDialog OpenFileDialog1 = new OpenFileDialog();

private void button1_Click(object sender, EventArgs e)
{
    OpenFileDialog1.Filter = @"All Files|*.*";
    object fileName = "";
    if (openFile.ShowDialog() == DialogResult.OK)
    {
        fileName = System.IO.Path.GetFullPath(OpenFileDialog1.FileName);
    }

    Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();
    Microsoft.Office.Interop.Word.Document wordDoc = null;       



    object missing = System.Type.Missing;
    document = App.Documents.Open(ref fileName, ref missing, ref missing, ref missing, 
                              ref missing, ref missing, ref missing, ref missing, 
                              ref missing, ref missing, ref missing, ref missing,
                              ref missing, ref missing, ref missing, ref missing);

您会注意到更改是将 fileName 赋值移动到 if 范围之前,然后将 fileName 值设置为 OpenFileDialog 中的文件。然后将其传递给互操作方法。我的建议是在 object fileName = "" 行设置一个断点并检查你的变量赋值。

我要补充一点,您应该更改您的代码,以确保如果您的 OpenFile 对话框的结果不正确,那么您应该添加一个 return 语句或通过其他模式来确保您没有执行以下代码将失败,因为用户已取消或关闭对话框。