简体   繁体   中英

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);

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)

Maybe you can try something like this?:

var folderName = Path.Combine(@_xmlFileName, "TestFile");
var fileName = $@"{folderName}\{DateTime.Now:yyyyMMddHHmmssfff}.dat";
File.WriteAllText(fileName, txRrcWellRecords);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM