none
How to Save word document in a folder which is created by Directory.CreateDirectory(docfile_path)? RRS feed

  • Question

  • I want to create a folder named as "test" inside this there will be another folder named as today's date "date" , i want to keep the the word document inside this date folder, please help.

    This block of code throws an error called file name is invalid.

    public string File_path; public string docfile_path; public string filename; private void button1_Click(object sender, EventArgs e) { string time = DateTime.Now.ToString("HH.mm.ss"); string date = DateTime.Today.ToShortDateString(); docfile_path = File_path+ "test" + date; Directory.CreateDirectory(docfile_path); filename = docfile_path + "worddoc"+"-" +".docx"; Word.Application app = new Word.Application(); Word.Document doc = new Word.Document(); try { doc = app.Documents.Open(filename); } catch { } Word.Paragraph oPara1; oPara1 = doc.Content.Paragraphs.Add(); oPara1.Range.Text = "Test Result"; oPara1.Range.Font.Bold = 1; oPara1.Format.SpaceAfter = 24; oPara1.Range.InsertParagraphAfter(); oPara1.Range.InsertParagraphAfter(); Word.Paragraph oPara2; oPara2 = doc.Content.Paragraphs.Add(); oPara2.Range.Text = "Test Name"; oPara2.Range.Font.Bold = 1; oPara2.Format.SpaceAfter = 24; oPara2.Range.InsertParagraphAfter(); doc.SaveAs2(filename); doc.Close(); doc = null; app.Quit(); app = null; }


    Friday, January 24, 2020 10:12 AM

All replies

  • The only problem I see with your code is that you are not inserting the proper path separator "\" when building your folder and filename. To avoid problems, it is recommended that you use System.IO.Path.Combine instead of concatenating strings with the "+" operator:

                  string time = DateTime.Now.ToString("HH.mm.ss");
                  string date = DateTime.Today.ToShortDateString();
    
                  docfile_path = Path.Combine(File_path, "test",  date);
                  Directory.CreateDirectory(docfile_path);
    
                  filename = Path.Combine(docfile_path, "worddoc.docx");
    

    Friday, January 24, 2020 10:55 AM
    Moderator
  • Are you aware that ToShortDateString creates strings with slashes in them?  Those will be interpreted as directory separators.

    I don't know how you could possibly hope to debug this without printing out the strings.  If you had done that, your problems would have been obvious.  Consider this example.  Let's say FilePath has the value "\Documents\Abc".  Your string docfile_path would be

        \Documents\Abctest1/25/2020

    and your string filename would be

        \Documents\Abctest1/25/2020worddoc-.docx

    And I hope it's clear why this is broken.  I assume you really want something like

       \Documents\Abc\test\2020-01-25\worddoc-.docx


    Tim Roberts | Driver MVP Emeritus | Providenza & Boekelheide, Inc.

    Saturday, January 25, 2020 10:57 PM