【问题标题】:Using OpenFIleDialog to get path for word document in C#在 C# 中使用 OpenFIleDialog 获取 word 文档的路径
【发布时间】:2019-05-20 00:28:00
【问题描述】:

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

【问题讨论】:

    标签: c# openfiledialog


    【解决方案1】:

    您当前将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 范围之前,然后将fileName 值设置为OpenFileDialog 中的文件。然后将其传递给互操作方法。我的建议是在object fileName = "" 行设置断点并检查您的变量分配。

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

    【讨论】:

    • 感谢您的回复。有效!!你介意告诉我如何保存到本地目录吗?谢谢。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-03-05
    • 1970-01-01
    • 1970-01-01
    • 2010-10-01
    • 2023-03-02
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多