Reputation: 53
Here is my code so far:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
namespace WordIterator
{
class LoadDocument
{
public static Document Default()
{
try
{
return AnyDoc(Filepath.Full());
}
catch
{
throw new Exception("Error loading default document.");
}
}
public static Document AnyDoc(string filepath)
{
try
{
object fileName = filepath;
Application wordApp = new Application { Visible = true };
Document aDoc = wordApp.Documents.Open(ref fileName, ReadOnly: false, Visible: true);
aDoc.Activate();
return (aDoc);
}
catch
{
throw new Exception("Error loading document " + filepath + "!");
}
}
}
}
//Main class
namespace WordIterator
{
class Program
{
static void Main(string[] args)
{
Document doc = LoadDocument.Default();
doc.SaveAs2(Filepath.Full().Replace(".docx", "_2.docx"));
Document doc2 =
LoadDocument.AnyDoc(@"C:\Users\netha\Documents\FSharpTest\FTEST\ftestdoc3_2.docx");
What i'm trying to do: Open a word document(do some stuff with it) Save it as _2.docx Then open _2.docx(do some stuff with it) However the second document keeps opening as read-only, I have it set as read-only false and I've even restarted my computer to make sure it shouldn't be read-only. Does anyone know why this is opening as Read-Only? Thank you for any assistance
Upvotes: 0
Views: 305
Reputation: 398
It is opening as read-only as you do SaveAs "_2.docx" and then you are trying to open the save document again. I would recommend you to close the active tab and then open the document.
You could use the following code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Word;
using Word = Microsoft.Office.Interop.Word;
using System.IO;
namespace WordIterator
{
class Program
{
static void Main(string[] args)
{
string FilePath = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test.docx");
Document doc = null;
Application wordApp1 =new Application();
Application wordApp2 = new Application();
string FilePath2 = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Test_2.docx");
try
{
object fileName = FilePath;
object fileName2 = FilePath2;
wordApp1 = new Application { Visible = true };
doc = wordApp1.Documents.Open(ref fileName, ReadOnly: false, Visible: true);
doc.SaveAs2(FilePath.Replace(".docx", "_2.docx"));
doc.Close();
Document doc2 = wordApp1.Documents.Open(ref fileName2, ReadOnly: false, Visible: true);
}
catch (Exception ex)
{
}
finally
{
System.Runtime.InteropServices.Marshal.ReleaseComObject(doc);
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp1);
}
}
}
}
Upvotes: 2