String.Format is not working as expected C# - c#

I'm trying to format content of my file like this:
0126252019-05-06 14:47:06 1098500020
But everytime I'm getting this results:
01262524. 5. 2019. 14:47:08 1098500020
Obliviously date and time are not formated as I wanted.
Here is my code:
StreamWriter file = new System.IO.StreamWriter("C:\\MyMainFolder\\MyFilesFolder\\" + 15050 + ".flr");
file.WriteLine(12625.ToString("D6") + string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020));
file.Close();
I've tried to format DateTime.Now as I wrote
string.Format("{0:yyyy-MM-dd HH:mm:ss}"
But looks like its not working
Thanks guys
Cheers!

You are passing DateTime.Now + " " + 1098500020 to string.Format which isn't going to be parsed by that format string you have specified. To fix that you should move the ).
However, you should create the entire string, including the prefix, with string.Format, or for clearer code use string interpolation, for example:
var someInteger = 12625;
var line = $"{someInteger:D6}{DateTime.Now:yyyy-MM-dd HH:mm:ss} 1098500020";

The problem is that + is applied as string concatenation in the expression below:
string.Format("{0:yyyy-MM-dd HH:mm:ss}", DateTime.Now + " " + 1098500020);
// ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
// C# makes this one string, and passes it for formatting.
Moving the concatenation that you plan to do inside the format string will fix the problem:
string.Format("{0:yyyy-MM-dd HH:mm:ss} 1098500020", DateTime.Now);

Related

Why is StreamWriter altering the text it writes to a file?

I have a class library, written in C#, that I use to write error and other information out to text or log files. The problem is that it is altering the text when it writes it to the file. It is being called by a vb.net application.
The text that should be written: 02-20-2017 08:17:42 - Personality Update() beginning:
The text that is actually being written: 02-20-2017 08:17:42 - Per42onaliA17 Up20aAe() beA.D.inninA.D.:
Below is the code that calls the method to write out the string.
errHandler.AddLineToLogFile(Me.MasterLogFileName, "Personality Update() beginning:")
Below is the method that gets called.
public void AddLineToLogFile(string logFile, string message, bool replaceExistingFile = false)
{
DateTime now = DateTime.Now;
using (StreamWriter writer = new StreamWriter(logFile, !replaceExistingFile))
{
writer.WriteLine(now.ToString("MM-dd-yyyy HH:mm:ss - " + message));
writer.WriteLine(" ");
}
}
Can anybody help me with this issue?
You pass the message as part of the date format. Parts that match a known format are replaced with values from now. Add the message after formatting your DateTime:
now.ToString("MM-dd-yyyy HH:mm:ss") + " - " + message
s = The second (42)
t = The first character of the AM/PM designator (A)
y = The year, from 0 to 99 (17)
d = The day (20)
g = The period or era (A.D.)
That's why
MM-dd-yyyy HH:mm:ss - Personality Update() beginning:
becomes
02-20-2017 08:17:42 - Per42onaliA17 Up20aAe() beA.D.inninA.D.:
A full list of custom date formats can be found here on MSDN
you are converting nowto string and your other text is inside that ToString method.
Seperate those two and it should be ok.
writer.WriteLine(now.ToString("MM-dd-yyyy HH:mm:ss") + " - " + message);
Try
DateTime now = DateTime.Now;
using (StreamWriter writer = new StreamWriter(logFile, !replaceExistingFile))
{
writer.WriteLine(now.ToString("MM-dd-yyyy HH:mm:ss") + "- " + message);
writer.WriteLine(" ");
}

Quickest/Best way to Format a string

I know this may seem a junior question and it should have been easy to find the solution by Googling it but I am stuck.
I am using C#.
I have this string:
20150824100112345 (for instance)
I wish to transform it to a new string like so:
2015\08\24\10\00\01\12\345
Is there a '1-liner' of code I can use to accomplish this please?
NB
Without 1st converting it to a datetime format
As said in the comments, you should really parse it to a DateTime and then turn that into a string.
But to parse a string as you asked you should use a Regex which can split it into groups.
If you don't want to parse to DateTime first (i.e. if you don't care about validity) and if the input is always formatted as your example (zero-padded, so 08 instead of 8), you can do with a few simple Substring() calls:
string input = "20150824100112345";
string output = input.Substring(0, 4) + #"\" // 2015
+ input.Substring(4, 2) + #"\" // 08
+ input.Substring(6, 2) + #"\" // 24
+ input.Substring(8, 2) + #"\" // 10
+ input.Substring(10, 2) + #"\" // 01
+ input.Substring(12, 2) + #"\" // 12
+ input.Substring(14, 3); // 345
Or in Regex:
string input = "20150824100112345";
string output = Regex.Replace(input,
"([0-9]{4})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{2})([0-9]{3})",
#"$1\$2\$3\$4\$5\$6\$7");

String.Replace Not modifying my String

I am trying to save a number of images and I'd like to use the DateTime to have distinct and identifiable Filenames.
So I create a String with the correct Path, add the datetime to it and remove the spaces, dots and colons.
String imagePath = "D:\\Patienten\\" + username;
imagePath += "\\"+DateTime.Now.ToString();
Console.WriteLine("WithFilename: " + imagePath);
imagePath.Replace(" ", "");
Console.WriteLine("Without \" \" : " + imagePath);
imagePath.Replace(".", "");
Console.WriteLine("Without \".\": " + imagePath);
imagePath.Replace(":", "");
Console.WriteLine("Output format: " + imagePath);
imagePath += ".png";
image.Save(imagePath);
According to the console output the String doesnt change at all.
Meaning all the Output Strings from Console.Writeline are identical.
I am using c# in visual Studio Express 2010 in case that makes a difference.
Can anyone find an Error here?
Thanks in advance!
Strings are immutable, the modified string will be a new string that is returned from the function
e.g.
imagePath = imagePath.Replace(" ", "");
Why strings are immutable
Why not just use DateTime.ToString() with a format and drop the dividers using that? Would be more efficient than performing several String.Replace() yourself:
string imagePath = "D:\\Patienten\\" + username + "\\" + DateTime.Now.ToString("yyyyMMdd hhmmssfff") + ".png";
You should use:
imagePath = imagePath.Replace(" ", ""); You should assign returned value
From the documentation (emphasis mine):
Returns a new string in which all occurrences of a specified string in the current instance are replaced with another specified string.
It is supposed to work like that. Use
imagePath = imagePath.Replace(" ", "");
instead.

How do I create a file based on the date?

string filename = DateTime.Today.ToString() + ".csv";
if(!File.Exists(filename))
File.Create(filename);
I thought this would work but it throws a 'format not supported' error. I just want a csv to be created in the directory alongside my .exe
I think the problem is that converting a DateTime to a string will generate a string with invalid filename characters, such as colons (:) and that will cause the create to fail.
You may want to use a format string to control the generated filename. e.g.
string filename = DateTime.Today.ToString("yyyy-MM-dd") + ".csv";
This is because DateTime.Today.ToString() contains slashes, which are not valid as part of a windows filename.
You can, however, do this: DateTime.Now.ToString("yyyyMMdd")
I'm guessing your locale has / / : (or similar confusing characters) in the date format. You should specify an explicit format - "yyyy MM dd" for example:
string filename = DateTime.Today.ToString("yyyy MM dd",
CultureInfo.InvariantCulture) + ".csv";
As everybody has pointed out, the default DateTime.ToString() formatting has invalid characters in it (for just about any region settings), so that
string filename = DateTime.Now.ToString() + ".csv";
generates a 'filename' like 2/18/2011 4:26:48 PM.csv -- which is invalid
if you want a date-time based name, try
string filename = DateTime.Now.ToString("yyyyMMddhhmmss") + ".csv";
to get something like 2011021804254.csv
you can add more formatting, just as long as it doesn't contain any of the following: \ / : * ? " < > |
Your date has slashes in it, try this instead
string filename = Datetime.Now.Ticks.ToString() + ".csv";

C# Convert strings to DateTime

I have 2 strings:
string d = "09/06/24";
string t = "13:35:01";
I want to take the strings and combine them to make a datetime variable:
newDT = Convert.ToDateTime(d + t);
Compiles but when it hits that line it fails..........any ideas?
DateTime.Parse(d + " " + t) should do it, the problem you were probably having is the lack of space inbetween the two variables, you were trying to parse:
"09/06/2413:35:01"
As you can see, this is not a valid date format.
does this work?
DateTime.Parse(d + " " + t);
Try this:
string d = "09/06/24";
string t = "13:35:01";
DateTime newDT = Convert.ToDateTime(d + " " + t);
If you have a specific format of date and time in the string, then consider using DateTime.TryParseExact which allows you to specify one or more formats to use for parsing.
Try:
Convert.ToDateTime(d + " " + t);
Convert.ToDateTime(d + " " + t) should also work.

Categories

Resources