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

时间:2019-05-20 00:28:00

标签: c# openfiledialog

我正在尝试使用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);

1 个答案:

答案 0 :(得分:0)

您当前将fileName设置为"filePath"作为字符串而不是实际路径。您会在代码中注意到,您正在filePath范围内设置if变量,该变量仅限于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范围之前,然后从OpenFileDialog中将fileName值设置为File。然后将其传递给互操作方法。我的建议是在object fileName = ""行上设置一个断点,并检查您的变量分配。

我要补充一点,您应该更改代码,以确保如果OpenFile对话框的结果不正确,那么您应该添加return语句或通过另一种模式来确保您不会执行将由于用户错误而失败的代码取消或关闭对话框。