我有这样的代码:
DialogResult result = openFileDialog1.ShowDialog();
if (result == DialogResult.OK)
{
Microsoft.Office.Interop.Word.Application newApp = new Microsoft.Office.Interop.Word.Application();
object Source = file;
object Target = Path.ChangeExtension(file, ".rtf");
object Unknown = Type.Missing;
newApp.Documents.Open(ref Source, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown, ref Unknown);
object format = Microsoft.Office.Interop.Word.WdSaveFormat.wdFormatRTF;
newApp.ActiveDocument.SaveAs(ref Target, ref format,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown, ref Unknown,
ref Unknown, ref Unknown);
newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
richTextBox1.LoadFile(Path.ChangeExtension(openFileDialog1.FileName, ".rtf")); }
当我调试我的程序时,它给出了一个System.IO.IOException错误(该文件正在最后一行代码中使用)。
答案 0 :(得分:0)
试试这个,看它是否有效:
var rtfFileName = Path.ChangeExtension(openFileDialog1.FileName, ".rtf");
richTextBox1.LoadFile(rtfFileName);
还要确保您要转换的文件未被任何其他进程使用。
答案 1 :(得分:0)
详细说明我在评论中所写的内容:
而不只是这样做:
newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
richTextBox1.LoadFile(Path.ChangeExtension(openFileDialog1.FileName, ".rtf")); }
试试这个:
newApp.Quit(ref Unknown, ref Unknown, ref Unknown);
// Maybe try and add a little sleep here anyway, so the filesystem
// gets a little time to update the file status.
//Thread.Sleep(100);
for( int i = 3 ; i > 0 ; --i )
{
try
{
richTextBox1.LoadFile(Path.ChangeExtension(openFileDialog1.FileName, ".rtf"));
break; // break out of for-loop if above line does not cause an exception
}
catch( IOException )
{
if( i > 0 )
{ // Retries left : wait a little and try again.
Thread.Sleep(100);
}
else
{ // No retries left : throw exception
throw;
}
}
}