Putting date in front of xml file name - c#

I have the following code:
XmlSerializer SerializeObj = new XmlSerializer(dirs.GetType());
TextWriter WriteFileStream = new StreamWriter(#"G:\project\tester.xml");
SerializeObj.Serialize(WriteFileStream, dirs);
WriteFileStream.Close();
I'm trying to put a date/time stamp in FRONT of the xml file name. Therefore, using this example, i'd have something like 0615_Tester.xml
Any ideas on how to do this? I want to make sure i can do date/time__[filename].xml and still specify it to be on my G:\
Thanks in advance.

This is Simply achieved with System.IO.Path:
string path = "G:\\projects\\TestFile.xml";
string NewPath = System.IO.Path.GetDirectoryName(path) +
System.IO.Path.DirectorySeperatorChar +
DateTime.Now.ToString() +
System.IO.Path.GetFileName(path);
You can add a using Reference to keep the Typing down, or Format the Date in any way you want as long as its a string. Using the DirectorySeperator Variable is reccommended, although you are probably programming for Windows If using .NET (Mono?)

Use string.Format - for example:
string dateString = "0615";
string fileName = string.Format(#"G:\project\{0}_tester.xml", dateString);
... = new StreamWriter(fileName);
Building up "dateString" should be trivial from DateTime.Now.

Try something like this:
string filePath = string.Format("G:\\project\\{0}tester.xml", Date.Now.ToString("DDMM"));
TextWriter WriteFileStream = new StreamWriter(filePath);

I'm assuming that the file already exists. So you will have to copy the file and delete the old one. Like this:
File.Copy(OldFileName, NewFileNameWithDate);
File.Delete(OldFileName);

string yourDateString = DateTime.Now.ToString(); // replace with any way you want to get your date string
string filename = "G:\\project\\" + yourDateString + "_tester.xml";
TextWriter WriteFileStream = new StreamWriter(filename);

Related

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

XmlWriter trimming my string

I am trying to return an XML string as a CLOB from Oracle stored procedure to C# string.
Then I am write this string to a file using XmlWriter class.
My code looks like following:
string myString= ((Oracle.ManagedDataAccess.Types.OracleClob)(cmd.Parameters["paramName"].Value)).Value.ToString();
string fileName = DateTime.Now.ToString("yyyyMMddHHmmss");
var stream = new MemoryStream();
var writer = XmlWriter.Create(stream);
writer.WriteRaw(myString);
stream.Position = 0;
var fileStreamResult = File(stream, "application/octet-stream", "ABCD"+fileName+".xml");
return fileStreamResult;
When I checked my CLOB output it returns completely to myString.
When I check my end result, XML file is trimmed at the end.
My string will be huge for ex: Length of 3382563 and more.
Is there any setting for XmlWriter to write the complete string to file.
Thanks in advance.
Sounds like all you want to do is grab some string value out of your Database, and write that string value in a text file. The string being xml does not actually force you into using an XML specific class or method unless you want to do XML specific operations, which I do not see in your snippet. Therefore, I suggest you simply grab the string value and spit it out in a file in the easiest way.
string myString = " blah blah blah keep my spaces ";
using (StreamWriter sw = new StreamWriter(#"M:\StackOverflowQuestionsAndAnswers\XMLWriterTrimmingString_45380476\bin\Debug\outputfile.xml"))
{
sw.Write(myString);
}

creating a new folder with todays date on specific folder

I am trying to create a new folder with todays date on specific given path:
string LocalDirectory = Directory.CreateDirectory(
DateTime.Now.ToString("I:\\test\\final test\\snaps\\dd-MM-yyyy"));
But I receive this error:
Cannot implicitly convert type 'System.IO.DirectoryInfo' to 'string'
As per the documentation for Directory.CreateDirectory, CreateDirectory returns a DirectoryInfo object, not a string.
So do this:
DirectoryInfo localDirectory = Directory.CreateDirectory(...
or this:
var localDirectory = Directory.CreateDirectory(...
(which will basically do the same thing)
The code can be written as :
String Todaysdate = DateTime.Now.ToString("dd-MMM-yyyy");
if(!Directory.Exists("I:\\test\\final test\\snaps\\" + Todaysdate)
{
Directory.CreateDirectory("I:\\test\\final test\\snaps\\" + Todaysdate);
}
Directory.CreateDirectory return a DirectoryInfo not string
you can try something like this
DirectoryInfo LocalDirectory = Directory.CreateDirectory(string.Format("I:\\test\\final test\\snaps\\{0}-{1}-{2}", DateTime.Now.Day, DateTime.Now.Month, DateTime.Now.Year));
to get the path as string
string strLocalDir = LocalDirectory.FullName;
Here is about the simplest way of creating a new folder named with todays date.
using System;
namespace CreateNewFolder
{
class Program
{
static void Main(string[] args)
{
string Todaysdate = DateTime.Now.ToString("-dd-MM-yyyy-(hh-mm-ss)");
{
Directory.CreateDirectory("c:/Top-Level Folder/Subfolder/Test" + Todaysdate);
}
}
}
}
Output of New folder name:
Test-02-05-2018-(11-05-02)
I put the hours, minutes and seconds inside some parentheses for clarity.
You can take out any part of the date to return only the time/date portion you want to call your folder. If you don’t want to call it “Test-02-05-2018-(11-05-02)” but simply have todays date as the name; like “02-05-2018”, then remove the “Test” from the “CreateDirectory” line but leave a blank space between -Subfolder/ and the closing quotation mark. Like this:
Directory.CreateDirectory("c:/Top-Level Folder/Subfolder/ " + Todaysdate);
Notice that I added a hyphen between the date parameters. This is just a visual separator for the date, you could also use a “space” as the separator.
I know this string is about 4 years old, but maybe this will help another newbie just starting out in C#.
Enjoy and share.
Take into account the culture
var rootOutputDir = #"I:\test\final test\snaps";
var Todaysdate = DateTime.Now.ToString(CultureInfo.CurrentUICulture.DateTimeFormat.ShortDatePattern.Replace("/", "-"));
Directory.CreateDirectory(Path.Combine(rootOutputDir, Todaysdate));
string path = Server.MapPath(#"/Content/");
path = Path.Combine(path,DateTime.Now.ToString('ddmmyyyy'));
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
I wanted to create directories for the year and then the month inside the year folder.
Here's what worked for me:
public void CreateDirectory()
{
string strArchiveFolder = (#"\\fullpath" + DateTime.Now.Year.ToString() + "\\" +
DateTime.Now.Month.ToString());
if (!Directory.Exists(strArchiveFolder))
{
Directory.CreateDirectory(strArchiveFolder);
}

Inserting on file path

Right now I have files being output to a path; "C:\Users\Daniel\Average.txt"
I'm trying to write a function to input the current timestamp after the "Average" but before the .txt
I know this is pretty elementary, but I don't know where to begin...
EDIT: I originally had it hardcoded;
string path = "C:\Users\Daniel\Average.txt";
You can just use this instead:
var outputFile = #"C:\Users\Daniel\Average.txt";
var outputDir = Path.GetDirectoryName(outputFile);
var fileWithTimeStamp = string.Format("{0}_{1}{2}", Path.GetFileNameWithoutExtension(outputFile),
DateTime.Now.ToString("yyyyMMddHHmmssffff"),
Path.GetExtension(outputFile));
var outputWithTimeStamp = Path.Combine(outputDir, fileWithTimeStamp);
My Test with LINQPad:
outputWithTimeStamp.Dump();
C:\Users\Daniel\Average_201304230828184465.txt
You can use Path.GetFileNameWithoutExtension.
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var name=Path.GetFileNameWithoutExtension(info.FullName);
name=(new[] { name, span, info.Extension }).Aggregate(String.Concat);
The name is what you want finally.
There's another way to composite with a full name:
var info=new FileInfo(#"C:\Users\Daniel\Average.txt");
var span=TimeSpan.FromTicks(DateTime.Now.Ticks).ToString();
var fullName=info.FullName;
var length=fullName.LastIndexOf(info.Extension);
fullName=fullName.Substring(0, length);
fullName=(new[] { fullName, span, info.Extension }).Aggregate(String.Concat);
I think something like this will work for you:
StreamWriter sw = new StreamWriter("C:\Users\Daniel\Average"+DateTime.Now.ToString(ADD_FORMAT_HERE) +".txt");
Then you will need to dump the contents into the file.
Try string.format:
string Today = DateTime.Now.ToString("MMMM_dd");
string name = string.Format(#"Average_{0}.txt",Today);
You can alter the DateTime.Now.ToString( to include seconds, minutes etc...
//have a string variable which holds your output
String output;
File.WriteAllText("C:\Users\Daniel\Average" + DateTime.Now + ".txt",output);
this will create the text file and writes the output to that file.

convert string to a xml file?

How to save a well formed xml string to a xml file ?
Thanks in advance...
Hi All.... I got the answer
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.LoadXml("WellFormedXMLString");
xmlDoc.Save(#"drive:\name.xml");
What's wrong with simply writing your string to disk?
using (StreamWriter writer = new StreamWriter(#"C:\file.xml"))
{
writer.Write("Xml data");
writer.Flush();
}
or if you want to "test" it:
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(data);
}
catch
{
// Fix it
}
doc.Save(#"C:\file.xml");
You can write any string to disk like so:
File.WriteAllText(#"c:\myfile.xml", yourXmlString);
If you have a string that is not a well-formed xml string and you want to convert that to some other format, you will have to give us some example of what you want to do.
I am no C# programmer, but I guess you need something like this:
xmlwriter tutorial
Save the string straight onto the disk. No need to convert it into XML.
Why do you need xml if it's just a string ? You could save a text file with the variabele name, and the string inside as variable value.
for example
MyTextVar1.txt would contain "MyTestSTring"
then you could get the var by:
var mystring = GetFileAsString( "MyTextVar1.txt" );
The xml document is a text file itself. you only need to change its extension.

Categories