Search code examples
c#ms-wordfilepathdocxfile-rename

Create a copy of a file in same location as original


The end-user supplies a path, indicating where the original document is.

string DocxFileName = "C:\\WorksArshad\\3.docx";

I'd like to create a copy of the document name 3.docx as 3Version1.docx and store the copy in the same directory as the original.

How do I get the whole path without the file name and extension?

(i.e.) I need to get the "C:\\WorksArshad\\" path alone.


Solution

  • FileInfo file = new FileInfo(Session.FileName); 
    string path = file.Directory.tostring();
    

    and then using

            string fileName = Path.GetFileNameWithoutExtension(Session.FileName);
            string DocxFileNamee = path + "\\" + fileName + "V1.docx";
            File.Copy(Session.FileName, DocxFileNamee, true);
    

    where in Session.FileName = "C:\WorksArshad\3.docx" and in path I'd get "C:\WorksArshad"

    requirement solved .


    Or

    File.Copy(Session.FileName, Path.Combine(Path.GetDirectoryName(Session.FileName)
    , Path.GetFileNameWithoutExtension(Session.FileName)+"V1.docx"),true);
    

    both the above gives the solution