Search code examples
c#filepathappsettingsconfigurationmanagertextwriter

How to get full path of file using File.WriteAllText in C#?


I have added key in settings file as <add key="Test.Directory" value="Data/Test/XML_Files" />.I need to pass this path to File.WriteAllText and concatenate as c:/Data/Test/XML_Files/TestFile but the path is taken only till c:/Data/Test/XML_Files.Please help to concatenate and get the full path

 var xmlFilePath = ConfigurationManager.AppSettings["Test.Directory"];
               string _xmlFileName = new DirectoryInfo(Path.GetFullPath(xmlFilePath));
    string Records = string.Empty;
                                using (StringWriter Writer = new Utf8StringWriter())
                                {
                                    xmlSerializer.Serialize(Writer, itemList);
                                    Records = Writer.ToString();
                                }
    File.WriteAllText(string.Format(@_xmlFileName + "'\'TestFile" + ".dat" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + Guid.NewGuid().ToString().Substring(1, 5) ), Records);

Solution

  • You error seems to be in those quotes added around the backslash before the TestFile constant. But I strongly suggest you to be more clear in your building of the filename and to use Path.Combine to create the final full filename

    string timestamp = DateTime.Now.ToString("yyyyMMddHHmmssfff") +  
                       Guid.NewGuid().ToString().Substring(1, 5);
    string file = Path.Combine(_xmlFileName, $"TestFile-{timestamp}.dat");
    File.WriteAllText(file, Records);
    

    Of course you could put everything in a single line, but this will not be a noticeable advantage of any kind for your performances and makes the understanding of the code really difficult. (Note, for example, that your original code has the datetime/guid part after the extension and this is probably an oversight caused by the complexity of the expression)