-2

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());
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • 3
    You probably want to use File.WriteAllText(ofd.FileName.ToString(), richTextBox1.Text) since it appears that it is already a string. WriteAllLines expect a string array, and by doing .ToArray() on a string you are creating an array of characters instead – dbso Jul 27 '21 at 05:51
  • `File.WriteAllLines(ofd.FileName, richTextBox1.Lines);` (if you want to use the `Lines` Property, which is an array of strings) – Jimi Jul 27 '21 at 05:54
  • As @.dbso and @.Jimi wrote, ToArray is not needed and Lines should be used instead. Just for information: [.NET / C# - Convert char\[\] to string](https://stackoverflow.com/questions/1324009/net-c-sharp-convert-char-to-string) –  Jul 27 '21 at 05:55
  • If what you quoted is verbatim, I wonder why it's an argumentnullexception – Caius Jard Jul 27 '21 at 06:22

1 Answers1

0

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.."

Cleptus
  • 3,446
  • 4
  • 28
  • 34
Caius Jard
  • 72,509
  • 5
  • 49
  • 80