Click here to Skip to main content
15,893,588 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi every one i working on a project and i needed to create word template with tags,
i created methods and every thing it work fine but when i get project on my laptap it appear with
this error
Attempted to read or write protected memory. '~/file/xxx.docx' This is often an indication that other memory is corrupt. in asp.net working with files
C#
public static bool WriteInfoToWordDoc(object fileName, Dictionary<string, object> data)
        {
            bool result = false;
            object missing = System.Reflection.Missing.Value;

            // setup Word.Application class.
            Microsoft.Office.Interop.Word.Application wordApp = new Microsoft.Office.Interop.Word.Application();

            // setup Word.Document class we'll use
            Microsoft.Office.Interop.Word.Document wordDoc = null;

            object readOnly = false;
            object isVisible = false;

            try
            {
                // set word to be not visible
                wordApp.Visible = false;

                // open the word document
                wordDoc = wordApp.Documents.Open(ref fileName, ref missing, ref readOnly, ref missing, ref missing,
                    ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing,
                    ref missing, ref missing);
                // activate the document
                wordDoc.Activate();
                
                foreach (string key in data.Keys)
                {
                    WriteData(wordApp, key, data[key]);
                }

                // save the document to correct destination
                wordDoc.SaveAs(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);

                // close the document
                wordDoc.Close(ref missing, ref missing, ref missing);
                result = true;
            }
            catch (Exception ex)
            {
                // nothing!
            }

            return result;
        }
private static bool WriteData(Microsoft.Office.Interop.Word.Application wordApp, string key, object value)
        {
            bool bResult = false;

            if (value != null)
            {
                string searchPattern = string.Format("#{0}#", key);
                bResult = FindAndReplace(wordApp, searchPattern, value);
            }

            return bResult;
        }

        private static bool FindAndReplace(Microsoft.Office.Interop.Word.Application wordApp, object findText, object replaceWithText)
        {
            bool result = false;
            object matchCase = true;
            object matchWholeWord = true;
            object matchWildCards = false;
            object matchSoundsLike = false;
            object matchAllwordForms = false;
            object forward = true;
            object format = false;
            object matchKashida = false;
            object matchDiacritics = false;
            object matchAlefHamza = false;
            object matchControl = false;
            object readOnly = false;
            object visible = true;
            object replace = 2;
            object wrap = 1;
            result = wordApp.Selection.Find.Execute(ref findText, ref matchCase, ref matchWholeWord, ref matchWildCards, ref matchSoundsLike, ref matchAllwordForms,
                ref forward, ref wrap, ref format, ref replaceWithText, ref replace, ref matchKashida, ref matchDiacritics, ref matchAlefHamza,
                ref matchControl);
            return result;
        }
// how i use this functionality
 string map = Server.MapPath(".");
                string path = map + "/Files/" + ContractTypesRow.ContractTypeRowID + ".docx";
                string FileName = map + "/Files/" + ContractsRow.ContractRowID + ".docx";
                string FileName2 = "Files/" + ContractsRow.ContractRowID + ".docx";
                bool res = Classes.WordInterop.SaveFile(path, ContractTypesRow.ContractTypeWordTemplateContent,this.Page);
                bool res2 = Classes.WordInterop.SaveFile(FileName, ContractTypesRow.ContractTypeWordTemplateContent,this.Page);
                if (res && res2)
                {
                    res = Classes.WordInterop.WriteInfoToWordDoc(FileName, data);
                    if (res)
                    {
                        System.Text.StringBuilder sb = new System.Text.StringBuilder();
                        sb.Append("<script type='text/javascript'>"); ;
                        sb.Append("window.open('" + FileName2 + "','_blank');");
                        sb.Append("</script>");
                        if (!ClientScript.IsStartupScriptRegistered("JSScript"))
                        {
                            ClientScript.RegisterStartupScript(this.GetType(), "JSScript", sb.ToString());
                        }
                    }
                }


this is my codes to use it.
thanks..
Posted

Quote:
Attempted to read or write protected memory. '~/file/xxx.docx'
I guess it is protected in your laptop. That might be due to limited access for Microsoft .NET to that folder or directory or file.

So, Right Click on the file, then check the Properties and see the Security Settings. You have give appropriate permissions,

Otherwise, try to run Visual Studio in Administrator mode and see if it works or not.
 
Share this answer
 
Comments
MohsenGolmehr 26-Jan-14 0:54am    
Hi Tadit Dash thanks for your answer...
i set permissions for current user to full control and run as administrator VS2010 and login with administrator account but its the same.
You have to give permission to .NET Framework, not the user.

Also Refer - http://www.codeproject.com/Articles/18240/COM-Interop-the-Hard-Way
Go to section "Vague System.AccessViolationException". It might help you.
hi Tadit Dash.
about My problem i decide to test problem on IIS and see whats coming i endup with this error


Retrieving the COM class factory for component with CLSID {000209FF-0000-0000-C000-000000000046} failed due to the following error: 80070005 Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)).


i dig on this error and i found it has to be permissions of Decoms on Component Services
the decom was Microsoft word when i opened my Component Services i did not found that Decom
i removed all office and instal agein after that Decom was in Component Services
i test application agein problem dispeared.

but it not fare because problem did not related to this matter or error was not clear.

thanks for help Tadit Dash.
 
Share this answer
 
Comments
Yes, sometimes it happens like that. :)
Anyway, great work. Well done.

Keep Coding. :)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900