How Convert all to one string? - c#

I need to convert this line in one string, because my method "DisplayMessage" only accept 1 argument, so how can I do this?
_userOptions.DisplayMessage("\nFile Generated: " +
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) +
"\nTime Elapsed: {0} minute(s) {1} second(s)",
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n");

It looks like your DisplayMessage method does not allow for the string format. Try putting this entire content (everything inside the parenthesis of DisplayMessage) inside a String.Format() method. That will make it one string and still allow for the multiple parameters you are passing.

Your string indicates that you want to call the static Format method on the String class, like so:
_userOptions.DisplayMessage(string.Format(
"\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)\n",
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)),
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10));
However, this will give you a problem, as you have more parameters than you have placeholders in the string.
Additionally, given comments regarding the use of "\n" as a new line delimiter, unless you have a specific need for that specific format (and it does not seem that you do, you aren't indicating you are writing to a file, or to something where the data is going to an external system), it's better to use Environment.NewLine, which you can use like so (note, this still does not address the fact you have more parameters than you do placeholders:
_userOptions.DisplayMessage(string.Format(
"{0}File Generated: {1}{0}Time Elapsed: {2} minute(s) {3} second(s){0}",
Environment.NewLine,
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)),
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10));

var msg = String.Format("\nFile Generated: {0}\nTime Elapsed: {1} minute(s) {2} second(s)\n", BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)), timeSpan.Minutes, timeSpan.Seconds);
_userOptions.DisplayMessage(msg);
This should do it...

I guess you want to use String.Format. This takes a string and replace {#} by the argument index.
Example:
String.Format("Hi {0}, welcome to Stack Overflow!", "ale");
You might want to have a look at How should I concatenate strings?

This is more elegant in my opinion:
string message = string.Format("{0}File Generated: {1}{0}Time Elapsed: {2} minute(s) {3} second(s) {4} milliseconds{0}",
"\n", BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)), timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
_userOptions.DisplayMessage(message);
Using Format there's no need to use any + operator on the strings.

I think, you can use a StringBuilder
StringBuilder sb = new StringBuilder();
sb.Append("\n");
sb.Append("File Generated: ");
sb.Append(BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)));
sb.Append("\n");
sb.Append("Time Elapsed: ");
sb.Append(timeSpan.Minutes);
sb.Append(" minute(s)");
sb.Append(timeSpan.Seconds);
sb.Append(" second(s)");
sb.Append();
_userOptions.DisplayMessage(sb.ToString());
but i think, you have some bug: you have 2 parameters but actually is 3

Try this:
string s= String.Format(
"\nFile Generated: " +
BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) +
"\nTime Elapsed: {0} minute(s) {1} second(s) {2} msec(s)\n",
timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10);
_userOptions.DisplayMessage(s);

Find below.
string str = String.Format("\n" + "File Generated: " + BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) + "\n" + "Time Elapsed: " + " {0} minute(s)" + " {1} second(s)", timeSpan.Minutes, timeSpan.Seconds, timeSpan.Milliseconds / 10 + "\n");
_userOptions.DiplayMessage(str);
Hope this helps.

Instead of {0} and {1}, just use your arguments directly:
_userOptions.DisplayMessage("\n" + "File Generated: " + BinaryWriter.GetBinaryFileName(filePath, Convert.ToInt32(logSelected)) + "\n" + "Time Elapsed:" + timeSpan.Minutes + "minute(s)" + timeSpan.Seconds + "second(s)" + timeSpan.Milliseconds / 10 + "\n");

Related

How to fix the following code showing this error

The following code below is concatenating the double variable .
For example first number is 2
And second is 3
It is adding them like this 2+3;
23
using System;
public static class Program
{
public static void Main()
{
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + num01 + num02);
Console.ReadKey();
}
}
You have not added 2 integers together, you have suffixed a string with 2 other numbers.
String concatenation is also 'slow'. You should use string.Format or string interpolation.
Console.WriteLine(string.Format("the result is {0}", num01 + num02) );
or
Console.WriteLine($"the result is {num01 + num02}");
The reson is that expression "the result is " + num01 + num02 is adding, which includes string, which makes the whole operation concatentaion, not addition of numbers! If at least one operand of + operator is string, it makes it concatenation.
Moreover, then every other operand is converted to string, so your numbers get converted to string and then concatenated.
To prevent that, force order of operation, so addition of your numbers is first, for example (already shown in other answers): "the result is " + (num01 + num02)
Now it will first sum two numbers, then concatenate with given string.
If you add the parentheses to the sum of the number, your code can work
double num01;
double num02;
Console.WriteLine("Add");
Console.Write("type a number: ");
num01 = Convert.ToInt32(Console.ReadLine());
Console.Write("type another number: ");
num02 = Convert.ToInt32(Console.ReadLine());
Console.WriteLine("the result is " + (num01 + num02));
Console.ReadKey();
but the best practice without a doubt is:
string.Format
"It is adding them like this 2+3; 23 "
That is because you are using + in a context where it treats 2 and 3 as strings and with strings + always perform concatenation, hence the result 23
What do you need to do to fix things?
Console.WriteLine("the result is " + (num01 + num02) );
Why does the above solution works?
Short answer: Operator precedence. Parenthesis has higher precedence and is evaluated first. When that happens num01 and num02 are treated as numbers and addition takes place. And now this sum value is treated like a string in + with "the result is "
What's going on: for
"the result is " + num01 + num02
we have
"the result is " + num01 which is "the result is 1" (adding double to string)
"the result is 1" + num02 which is "the result is 12" (adding double to string)
what can you do: put (..) and have "the result is " + (num01 + num02):
num01 + num0 which is 3 (adding two doubles)
"the result is " + 3 which is "the result is 3" (adding double to string)
So you can either put (...)
Console.WriteLine("the result is " + (num01 + num02));
or (better way) use string interpolation and let .net compute the sum for you:
Console.WriteLine($"the result is {num01 + num02}");
or formatting:
Console.WriteLine("the result is {0}", num01 + num02);

Why are my results not being written to the Console like I expect them to?

I'm writing a program that lets you input two numbers and gives you all the math answers for it. So like multiplication, division, etc. Problem is when I run it, it asks for the input and then it just shows all the operator strings but empty and then ends there.
I tried making an array and then setting that equal to the operators in the Console.WriteLines but that didn't work.
static void Main(string[] args)
{
Console.WriteLine("Input any two numbers.");
var number1 = int.Parse(Console.ReadLine());
var number2 = int.Parse(Console.ReadLine());
Console.WriteLine("Addition: ", + (number1 + number2));
Console.WriteLine("Division: ", + (number1 / number2));
Console.WriteLine("Subtraction: ", + (number1 - number2));
Console.WriteLine("Multiplication: ", + (number1 * number2));
}
You wrote:
Console.WriteLine("Addition: ", + (number1 + number2));
You meant to write
Console.WriteLine("Addition: " + (number1 + number2));
Note that you added an extra comma.
This code is legal, but bad style. See below for better ways to write this.
What is the meaning of the code you wrote? Console.WriteLine lets you do this:
Console.WriteLine("Addition:{0} + {1} = {2}", number1, number2, number1 + number2);
That is "replace {0} with the first thing following, {1} with the second thing, and so on".
So the code you wrote was "replace {0} with the value of +(number1+number2), but you don't have a {0}, so, nothing happens.
Today would be a great day for you to learn about interpolated strings:
Console.WriteLine($"{number1} + {number2} = {number1 + number2}");
Notice the $ that indicates that the string is interpolated; expressions inside {} will be evaluated and turned into text.
Concatenation with string returns string but you have to write it like that: Console.WriteLine("Division: "+(number1 / number2));
You can also use placeholder Console.WriteLine("Division: {0}",(number1 / number2));
or string interpolation Console.WriteLine($"Division: {number1 / number2}");

How to get values from a TextBox and apply a format automatically?

Below is my place holder in which the values are hard-coded:
var abc = string.Format($"{123456} {123456} {12345} {123456789012345} {12345678901234567890123} {1234} {1234} {123} {1234567890123} {123456789012345} {1} {123456789012345}
{123} {12} {12345678901234567890} {1} {1234}");
File.WriteAllText(
FilePath + "\\CDR-" +
DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + ".txt", abc);
But I want to get values from the TextBox automatically in these placeholders.
Suppose below is my TextBox and its value:
123456 123456 12345 123456789012345 12345678901234567890123
1234 1234 123 1234567890123 123456789012345 1 123456789012345
123 12 12345678901234567890 1 1234
You can split the input string using the sequence separator (it appears to be a white space here), and use the string array generated by string.Spilt() as the input of the string.Format() method.
Something like this:
string filePath = #"[Some Path]";
string[] values = textBox1.Text.Split();
var format = string.Format(
"{0} {1} {2} {3} {4} {5} {6} {7} {8} {9} {10} {11} {12} {13} {14} {15} {16}",
values);
File.WriteAllText(Path.Combine(filePath,
"CDR-" + DateTime.Now.ToString("MM-dd-yyyy HH-mm-ss") + ".txt"),
format);
If you have a different separator, specify it as a parameter of the Split() method.
The white space is the predefined character. No need to specify it in this case. With different symbols:
A single character: [someString].Split(',');
More than one: [someString].Split(new[] {',', '+'});
Strings: [someString].Split(new[] { ",", "+" }, StringSplitOptions.RemoveEmptyEntries);

How to format a string with fixed width fields

I'm was wondering if there is a way to format a string to format a string, what I mean is, I have a foreach loop that get a information from some files and how many records has each file, as the length of each file is different the format is change.
My example is, I have 3 files:
1.- MyFile1.txt RecordCount: 5
2.- anotherfile.txt RecordCount: 8
3.- MyTestFile.doc RecordCount: 17
As you can see are not formated, I want something like this:
1.- MyFile1.txt RecordCount: 5
2.- anotherfile.txt RecordCount: 8
3.- MyTestFile.doc RecordCount: 17
does not matter the length of the file, RecordCount will be in the same place.
What I have is this:
foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
{
BodyMessage.Append((index + 1) + ". " + file.Name + " Record Count: " + File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString() + "\n");
index++;
}
Any idea?
You can try using \t in your strings which will insert a tab or you can try padding each portion so they always take up the same amount space.
For example:
string fileName = file.Name.PadRight(50);
will ensure that the string fileName is at least 50 characters long. I say at least because you could always have a file name that is larger than 50 characters.
foreach (RemoteFileInfo file in MySession.EnumerateRemoteFiles(directory.RemoteDirectory, directory.RemoteFiles, EnumerationOptions.None))
{
int lines= File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
string appending = String.Format("{0,2}.- {1,-18} RecordCount: {3}", file.Name, lines);
BodyMessage.Append(appending);
index++;
}
See MSDN: String.Format Method.
Firstly, use string.Format, rather than concatenation:
int lineCount = File.ReadAllLines(Path.Combine(directory.LocalDirectory, file.Name)).Length.ToString();
string message = string.Format("{0}. {1}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
To answer your question, you can align text within a formatted string using the following syntax:
string message = string.Format("{0}. {1,-10}\t Record Count: " {2}\n", (index + 1), file.Name, lineCount);
The additional -10 will ensure that the inserted text is left-padded to 10 characters.
I think you can use PadRight or PadLeft function for this.
string _line = item.FirstName.PadRight(20) + item.Number.PadRight(20) + item.State.PadRight(20) + item.Zip.PadRight(20);
file.WriteLine(_line);

Row-like string with even spacing in between values

I'm trying to add multiple lines and with different sections to a ListBox, and am required to use "\t" for creating a layout.
listBox.Items.Add(emp[index].first + "\t\t" + emp[index].last + "\t\t" + emp[index].number + "\t\t" + emp[index].department + "\t\t" + "Annual Salary: " + (emp[index].annualSalary).ToString("c") + ", Annual Bonus: " + (emp[index].annualBonus).ToString("c"));
Just one example line.
It comes out looking like: (without the dots)
Mary.......Sue................778-435-2321.....Accounting.....Annual Salary: $33,000.00
Trevor....Joseph...........604-894-2902.....Marketing.......Annual Salary: $52,000.00
Steve......Collin.............778-234-5432.....Finance..........Annual Salary: $48,500.00
George...........Watson..........604-910-2349.....Technical.......Annual Salary: $25,000.00
Sally.......Henderson.....604-654-2325.....Sales..............Annual Salary: $12,000.00
Jenny.....Motgomery.....604-692-4932.....Data Ana.......Annual Salary: $12,000.00
Can anyone explain why it's displaying all wonky, and how I might fix this?
I've searched online, but couldn't find any results using \t for layout.
First thing, I highly suggest using a pattern instead of concatenating your strings using plus sign. This will help you see things more clear:
string pattern = string.Format("{0}\t\t{1}\t\t{2}\t\t{3}\t\tAnnualSalary: {4}, Annual Bonus: {5}",
emp[index].first,
emp[index].last,
emp[index].number,
emp[index].department,
emp[index].annualSalary).ToString("c"),
emp[index].annualBonus);
The answer to your question is that you are using tabs assuming they will fill the space for you, but they won't. You need to use advanced features of
string.Format or string.Pad
Full answer can be found here: Formatting a C# string with identical spacing in between values

Categories

Resources