0

I've written some code to take a word doc and copy it to the clipboard. In this word doc there is 800+ strings on their own line.

I'm trying to split the document by line, insert it into a list and then for testing purposes display one of the lines. However, I am getting an empty message box. (Previous tests show the list does indeed contain 800+ rows. They may just be null because of wrong code.)

Here's my code:

string myData = data.GetData(DataFormats.Text).ToString();

List<string> myList = new List<string>(myData.Split(new char[]{'\r','\n'}));

MessageBox.Show(myList[5]);

What am I doing wrong?

The Muffin Man
  • 19,585
  • 30
  • 119
  • 191
  • Could be displaying an empty string entry in the list. There is a string split parameter to tell it to not add empty strings to the result list. – asawyer Mar 25 '11 at 19:27
  • I got rid of `\r` and it worked :/ – The Muffin Man Mar 25 '11 at 19:27
  • That could be because some programs and some systems use just the Newline (\n) character while others use a combination of the Return (\r in C# and CR on the ASCII charts) and Newline (\n in C# and LF on the ASCII charts) character so even your modified code will work with some input documents but not others. Using System.Environment.Newline will cover you for both. http://en.wikipedia.org/wiki/Newline – David Mar 25 '11 at 19:31
  • See here for a similar question with a better explanation than mine above. http://stackoverflow.com/questions/238002/replace-line-breaks-in-a-string-c – David Mar 25 '11 at 19:34

1 Answers1

5

try

myData.Split(new string[]{Environment.NewLine}, StringSplitOptions.RemoveEmptyEntries)
Bala R
  • 107,317
  • 23
  • 199
  • 210
  • Would you happen to know how to dispose of a word document? When I run the code again it says the doc is locked for editing. – The Muffin Man Mar 25 '11 at 19:38
  • You need to call the Quit() function of the Application object. However, I've found that this doesn't always work, so I also use System.Diagnostic.Process to kill the instance of Word. See http://msdn.microsoft.com/en-us/library/system.diagnostics.process.kill.aspx for the Kill and http://msdn.microsoft.com/en-us/library/aa220368(office.11).aspx for the Quit – David Mar 25 '11 at 19:43