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

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(" ");
}

Related

String.Format is not working as expected 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);

Get a specific word from a line read from a .txt

right now I am reading some lines from a .txt.
Lets say, a user enters his name and in the .txt will be saved "Logged in {username} on 13/04/2016 at 10:55 am".
(Just an example.)
Now I want to read the .txt and print only specific parts into a textbox.
Meaning, in the textbox shall appear "{Username} - 13/04/2016 - 10:55 am".
So far, I am able to read from the .txt and print the whole line.
private void button_print_results_Click(object sender, RoutedEventArgs e)
{
int counter = 0;
string actual_line;
System.IO.StreamReader file_to_read =
new System.IO.StreamReader("myText.txt");
while ((actual_line = file_to_read.ReadLine()) != null)
{
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
file_to_read.Close();
}
Is there a way, to reach this without overwriting the whole file?
And no, I can't change the format how the names etc. are saved.
(I used them here for a better understanding, the actual lines I need to read/check are different and auto-generated).
I don't expect full working code, it would be just great if you could tell me for which commands I need to look. Been a long time since I last worked with c#/wpf and I never worked much with Streamreader...
Thanks
I think regular expressions is the best tool for what you're trying to achieve. You can write something like this:
Regex regex = new Regex("Logged in (?<userName>.+) on (?<loginTime>.+)");
while ((actual_line = file_to_read.ReadLine()) != null)
{
Match match = regex.Match(actual_line);
if (match.Success) {
string loginInfo = string.Format("{0} - {1}", match.Groups["userName"], match.Groups["loginTime"]);
textBox_results.Text = textBox_results.Text +"\n"+ loginInfo;
}
}
There are couple of possible solutions for this. One most straight forward way for your case would be to use Substring and Replace.
Since the earlier string is always Logged in (note the last space) and you simply want to get the rests of the string after the phrase, replacing only the preposition of time words (" on ", " at ") with dash (" - ") you could take advantage on that:
string str = "Logged in {username} on 13/04/2016 at 10:55 am";
string substr = str.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
In your implementation, this is how it look like:
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line.Substring(("Logged in ").Length) //note the last space
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text +"\n"+ actual_line;
counter++;
}
(Note: the solution above assumes the {username} does not contain spaced preposition of time words - which would almost likely be the case for a {username})
You could split the actual_line String so you get an array of Strings. And then fill the Strings you want to show in the TextBox into it.
string[] values = actual_line.Split(' ');
textBox_results.Text = textBox_results.Text + "\n" + values[2] + " " + values[6] + " " + values[7];
The text in the TextBox for example is "{username} 10:55 am"
You can use Regex for better performances as #Dmitry-Rotay suggested in the previous comment, but if you jave a not-so-big file your loop+string manipulations is an acceptable compromise.
Always use Environment.NewLine instead of "\n", it's more portable.
while ((actual_line = file_to_read.ReadLine()) != null)
{
actual_line = actual_line
.Replace(("Logged in "), String.Empty)
.Replace(" on ", " - ")
.Replace(" at ", " - ");
textBox_results.Text = textBox_results.Text
+ System.Environment.NewLine
+ actual_line;
counter++;
}

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

How can I add a SPACE halfway through a string value?

I'm trying to create a STRING in JSON format. However, one of the fields (from my editing/removing ALL spaces) now leaves a line like "START":"13/08/1410:30:00". However, I want to add a space between the date and time? I have tried using the ToCharArray() method to split the string, but I am at a loss as to how to add a space between the DATE and TIME part of the string?
For Example, i am trying to get: "START":"13/08/14 10:30:00" but instead am getting
"START":"13/08/1410:30:00"
Please note. The length of the string before the space requirement will always be 17 characters long. I am using VS 2010 for NETMF (Fez Panda II)
If the split position is always 17, then simply:
string t = s.Substring(0, 17) + " " + s.Substring(17);
Obviously you will have to sort the numbers out, but thats the general idea.
String.Format("{0} {1}", dateString.Substring(0, 17), dateString.Substring(17, dateString.Length - 17);
Or you can use the StringBuilder class:
var finalString = new StringBuilder();
for (var i = 0; i < dateString.Length; i++){
if (i == 17)
finalString.Add(" ");
else
finalString.Add(dateString.ToCharArray()[i]);
}
return finalString.ToString();
If the date time format always the same you can use string.Insert method
var output = #"""START"":""13/08/1410:30:00""".Insert(17, " ");
Strings in .Net are immutable: you can never change them. However, you can easily create a new string.
var date_time = dateString + " " + timeString;

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