需要帮助C#错误:对象引用未设置为对象的实例

需要帮助C#错误:对象引用未设置为对象的实例,c#,object,reference,instance,C#,Object,Reference,Instance,您能帮我解决以下错误信息吗 “对象引用未设置为对象的实例。” 我用注释和** 请看下面 private static void _GenerateWord(string fname, string reportStartDate, string reportEndDate) { var word = new Microsoft.Office.Interop.Word.Application(); var doc = new Mic

您能帮我解决以下错误信息吗

“对象引用未设置为对象的实例。”

我用注释和
**

请看下面

private static void _GenerateWord(string fname, string reportStartDate, string reportEndDate)
        { 
            var word = new Microsoft.Office.Interop.Word.Application();
            var doc = new Microsoft.Office.Interop.Word.Document();
            word.Visible = false;
            object missing = Type.Missing;

            object fileName = (@LetterTemplateLocation + LetterName);

            doc = word.Documents.Open(ref fileName);


            doc.Activate();//**Error message here "Object reference not set to an instance of an object."**

            string dateWithFormat = DateTime.Now.ToString("MMMM d, yyyy");

            //**Error message here "Object reference not set to an instance of an object."**
            foreach (Microsoft.Office.Interop.Word.Range tmpRange in doc.StoryRanges)
            {
                _FindAndReplace("<date>", dateWithFormat, tmpRange, missing);

                _FindAndReplace("<filename>", fname, tmpRange, missing);

                _FindAndReplace("<startdate>", reportStartDate, tmpRange, missing);

                _FindAndReplace("<enddate>", reportEndDate, tmpRange, missing);
            }

            if (doc != null)
            {
                doc.Close(ref missing, ref missing, ref missing);
                word.Application.Quit(ref missing, ref missing, ref missing);
            }
        }
private static void\u GenerateWord(字符串fname、字符串reportStartDate、字符串reportEndDate)
{ 
var word=新的Microsoft.Office.Interop.word.Application();
var doc=新的Microsoft.Office.Interop.Word.Document();
可见字=假;
对象缺失=类型。缺失;
对象文件名=(@LetterTemplateLocation+LetterName);
doc=word.Documents.Open(参考文件名);
doc.Activate();//**此处的错误消息“对象引用未设置为对象的实例。”**
字符串dateWithFormat=DateTime.Now.ToString(“MMMM d,yyyy”);
//**此处的错误消息“对象引用未设置为对象的实例。”**
foreach(doc.StoryRanges中的Microsoft.Office.Interop.Word.Range tmpRange)
{
_FindAndReplace(“”,dateWithFormat,tmpRange,缺失);
_查找并替换(“”,fname,tmpRange,缺失);
_查找和替换(“”,报告开始日期,tmpRange,缺失);
_FindAndReplace(“”,reportEndDate,tmpRange,缺失);
}
如果(doc!=null)
{
单据关闭(参考缺失、参考缺失、参考缺失);
word.Application.Quit(缺少ref,缺少ref,缺少ref);
}
}

谢谢。

作为惯例,需要检查文档是否为空

如果(doc!=null){…}


还需要按照其他人的建议评估有效文件。

可能的重复文件看起来像
doc
get的null。您确定
fileName
是现有word文档文件的路径吗?我会先检查fileName是否存在。。bool found=File.Exist(fileName)@Idan Arye:Yes,
fileName
是指向现有word模板的路径。谢谢为什么您的文件名被键入为对象。文档。Open接受字符串参数。谢谢。我要补充一点。