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.
Related
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);
how can I get a value of the string after last'/'
string path=http://localhost:26952/Images/Users/John.jpg
I would like to have as a result something like :
John.jpg
I think using Path.GetFileName method is a better way instead of string manipulation.
string path = "http://localhost:26952/Images/Users/John.jpg";
var result = Path.GetFileName(path);
Console.WriteLine(result); // John.jpg
Split by '/' and get the last part:
var url = "http://localhost:26952/Images/Users/John.jpg";
var imageName = url.Split('/').Last();
I'm writing a small WPF Application which helps my company to update costumer projects. I have a list of SQL-Files which I have to execute. Now these scripts are always written with a "USE [Insert_Database]". I read the whole content of a script into a string, but my Replace method doesn't seem to do anything.
string content = File.ReadAllText(file);
content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
String.Replace returns the modified string, so it should be:
content = content.Replace(....);
This method does not modify the value of the current instance.
Instead, it returns a new string in which all occurrences of oldValue
are replaced by newValue.
You can use replace function as follow on strings
str = str.Replace("oldstr","newstr");
if oldstr is found in the str then it will be replaced by new str
You aren't using new value when you call replace.
string content = File.ReadAllText(file);
content = content.Replace("Insert_Database", Database.Name);
SqlScriptsList.Add(new SqlScriptModel {Name = Path.GetFileName(file), Path = file, ScriptContent = content});
for reference: the MSDN doc for replace https://msdn.microsoft.com/en-us/library/system.string.replace(v=vs.110).aspx
I have strings that have a directory in the following format:
C://hello//world
How would I extract everything after the last / character (world)?
string path = "C://hello//world";
int pos = path.LastIndexOf("/") + 1;
Console.WriteLine(path.Substring(pos, path.Length - pos)); // prints "world"
The LastIndexOf method performs the same as IndexOf.. but from the end of the string.
using System.Linq;
var s = "C://hello//world";
var last = s.Split('/').Last();
There is a static class for working with Paths called Path.
You can get the full Filename with Path.GetFileName.
or
You can get the Filename without Extension with Path.GetFileNameWithoutExtension.
Try this:
string worldWithPath = "C://hello//world";
string world = worldWithPath.Substring(worldWithPath.LastIndexOf("/") + 1);
I would suggest looking at the System.IO namespace as it seems that you might want to use that. There is DirectoryInfo and FileInfo that might be of use here, also. Specifically DirectoryInfo's Name property
var directoryName = new DirectoryInfo(path).Name;
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);