我正在尝试使用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);
答案 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语句或通过另一种模式来确保您不会执行将由于用户错误而失败的代码取消或关闭对话框。