Morgan Romano

Morgan Romano

  • NA
  • 1
  • 4.3k

How do I change a MS Word file name that has data from File1.doc to File2.doc in C#

Nov 11 2010 4:20 PM
Hi,
  I have a text file that has 50 thousand lines. Each line consist information about a specific client and a word documents name. Ex:  J.P. Morgan  14/33 5th Avenue, New York City, 11/10/2010 report.doc (separated by tab)

What I am trying to do is reading this text file one line at a time and take this MS word file "report.doc" and rename it to "November.doc". However the content of the "report.doc" should remain as it is once I change the name to "November.doc".

I already implanted  a C# class and that is working fine to rename text file but not .doc file. I try both File.Move and File.Copy. If I try to change the name of a file that had a .doc extension I get file creation exception errors.

It would be great if you can educate me to solve this puzzle. 

Many Thanks 

Morgan

Jsaon,
   Somehow reply windows does not allow me to write so thanks you for yours response. I already try the code you mentioned and it works for .txt file rename but does not work for .doc file. Perhaps it could be done using references "Microsoft.Office.Interop. Word" however I do not know how. 

Any idea anyone...?


Here just a simple program to test 

using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace SimpleWodFileRename
{
    class Program
    {
        static void Main(string[] args)
        {
            try 
            {

                //string path = "c:\\netProgram\\First1.txt";
                //string path2 = "c:\\myPerlProg\\NewFirst1.txt";

                string path = @"c:\netProg\Dept.doc";
                string path2 = @"c:\msDocuments\NewDept.doc";

                File.Move(path, path2);
            }
             catch (Exception e)
            {
                Console.WriteLine("The process failed: {0}", e.ToString());
            }
        }
    }
}


The commented lines where I am renaming the .txt file works. However I commented those lines and when I am trying to rename .doc files I get exception. 

Jason,
   Thanks again and yes my file is there and I created it open it several times using MS Word. The directory (c:\msDocuments) does exist and it has correct permission to read/write etc. 

I am sure a MS Word doc can not me rename this way and some references along with some code needs to be implement in order this things to work. 

Anyone here can HELP ME PLEASE....

Thanx





Answers (4)