Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 24 days ago.
Improve this question
I am a new user to C# and I am having difficulty with one last thing to finish this script I am working on. I am in .NET 5.0. I am working on writing some results out to a csv file but when I use the string.Format() method, I am only getting the first value returned to the console, or the csv for that matter.
string newLine = string.Format("Value1", "Value2");
Console.WriteLine(newLine);
I am inside of a loop, and all lines are being returned, buy only Value1 is being returned on each line, not Value2. Any help would be appreciated.
I don't think you understand how string.Format() works at all. The first argument is a base string, which should include placeholders (ie: {0}, {1}, etc). Additional arguments then fill in the placeholders in order.
So if you want CSV data, it sounds like you want something more like this:
string newLine = string.Format("{0},{1}", "Value1", "Value2");
Console.WriteLine(newLine);
Or from an array like this:
string[] row = {"Value1", "Value2"};
string newLine = string.Format("{0},{1}", row);
Console.WriteLine(newLine);
Or maybe you'd prefer string.Join(), which can handle an arbitrary number of values without needing placeholders:
string[] row = {"Value1", "Value2"};
string newLine = string.Join(",", row);
Console.WriteLine(newLine);
But really, even simple CSV files have a surprising number of edge cases and gotchas, and you'll likely be MUCH better off to get a CSV library from NuGet.
Related
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 1 year ago.
Improve this question
I was trying to make a save dialog from a rich text document but I keep getting an error on the text.
Error:
ArgumentNullException
Argument 2: cannot convert from 'char[]' to 'string[]'
I'm new to c# so I'm not sure how to fix this.
System.IO.File.WriteAllLines(ofd.FileName.ToString(), richTextBox1.Text.ToArray());
Use a different method:
System.IO.File.WriteAllText(ofd.FileName, richTextBox1.Text);
I'd recommend avoiding to use Lines for this; it's a waste of resources to split the text into N strings only to write them all back to a combined file
Why didn't your first attempt work? WriteAllLines requires an array of strings. If you call .ToArray() on a string you get an array of characters; strings and characters are very different things.
ToArray() is a LINQ method that works because a string can be treated as an enumerable sequence of char. Typically it's very rare that you would do so and you would probably use the dedicated string.ToCharArray() method if you did want a char array from a string. Mostly I use it when splitting strings on multiple characters: someString.Split(".,?!'-/:;()".ToCharArray()); as it's more readable than putting each char separately
You're more likely to use ToArray() later on for things like filtering one array using LINQ and turning the result into an array again:
Person[] smiths = people.Where(person => person.LastName == "Smith").ToArray();
Other points:
OpenFileDialog's FileName is already a string; you don't need to ToString() it
Please get into the habit of renaming your controls after you add them to a form (top of the properties grid, the (Name) line, takes two seconds). It's a lot easier for us on the internet (and you in 3 weeks' time) to be able to read usernameTextBox and go "oh, that's the username textbox" than it is to be wondering "is it textbox56 or textbox27 that is the username? I'll just go into the form designer and check.."
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
An public string ItemSubType which is assigned a string "primary" by another script is somehow not equal to the string "primary". I've checked for empty characters but there isn't any. I've been absolutly stumped by this but also interested in how this is happening.
Debug.Log("---primary---");
Debug.Log("---" + ItemSubType + "---");
if(ItemSubType != "primary")
{
Debug.Log("This is ridiculous!");
}
Here is logs:A picture of the log
Thank you all for the comments!
After browsing through some other questions, I found .Trim().
Mystically there seems to be an invisible character in the string that isn't a whitespace character, as would be evident by the lack of spaces when adding '---' to either side.
By doing this:
ItemSubType = ItemSubType.Trim();
It fixed the Issue. To give some context, I pulled the string data from a csv file. I checked the file for any extra spaces but there wasn't any. Not sure if this is related tho.
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 2 years ago.
Improve this question
I have an oData api url where I am trying to replace querystring values with dynamic values.
I wish to pass comma separated string to one of my placeholder but I am getting error:
"Input string is not in correct format".
Here, in my "$select" placeholder I am passing comma separated string but it's failing with above error.
Here is my code:
string test = string.Format("https://myapiUrl/views/my_view_name?$filter=customer_id eq {} & $select={}", "101", "price,createdOn");
Can anybody guide me on this ?
Thanks !!!
string test = string.Format("https://myapiUrl/views/my_view_name?$filter=customer_id eq {0} & $select={1}", "101", "price,createdOn");
Have to add the number of the index of the parameter to the curly braces. (zero based)
Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 4 years ago.
Improve this question
you can see that value is 74 but its not going inside the if why?
Because you have a space in TEMP. " 74". The two values are not equal because the second one TEMP2 is "74" without the space.
Try using Trim on your values to remove whitespace:
string temp = ids[i].Trim();
string temp2 = raditem.Value.ToString().Trim();
Also, always use the .Equals overload for the String class, as you can control the culture for the string comparison. In this case it doesn't matter because they're numerals but it could matter if you want to compare to alphabetical strings where you want "A" to equal "a" and so forth.
Furthermore, if you are sure your array contains only numbers, I could recommend converting the values to numbers before comparing them.
// one way to validate is wrap this in a try-catch and handle input format error.
int temp = Convert.ToInt32(ids[i].Trim());
That way if you have a case where there aren't numbers, you could validate and complain to the user or whatever you want.
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Improve this question
My program has been receiving this error recently and I am not sure why. The code that is triggering it is:
foreach (var lot in item.LotNum.Split('|'))
{
string vendor = string.Empty;
if (lot.Trim().Contains("-"))
vendor = lot.Trim().Substring(0, item.LotNum.IndexOf("-"));
}
LotNum = "br549 | BR549 | 570-PRIOR" and lot is "570-PRIOR" (without quotes) when the error triggers. I've not used IndexOf before and so I am not sure what is wrong with the string that is being sent in. I want to check for what causes the error beforehand because the exception is stopping the program and the bad data will be there for a while until it is fixed, and more may be added in the future.
Any help would be appreciated!
New answer according your code update:
var lots = item.LotNum.Split('|');
foreach (var lot in lots)
{
string vendor = string.Empty;
if (lot.Contains("-"))
vendor = lot.Substring(0, lot.IndexOf("-")).Trim();
}
Again, you were using IndexOf for a variable different than the one you want to get a substring
You are using IndexOf for a variable different than the one you want to get a substring, so, the index will be out of range.
Try with: edited
variable = variable.Trim();
int index = variable.IndexOf("-");
if (index > 0)
variable.Substring(0, index);
Another way to do this is to check for the existence of the character using Contains, and if it's found use the IndexOf, otherwise just use the Length of the string (and put Trim at the end to avoid issues with using the Length after trimming):
variable.Substring(0, variable.Contains('-')
? variable.IndexOf('-')
: variable.Length)
.Trim();