-1

I am receiving an error:

"Use of unassigned local variable 'PostData'"

when compiling the following statements below within a method. My intent is take a "string" value containing an XML SOAP header and convert it to a XMLDictionaryWriter object. See my code below:

Stream PostData;
byte[] buffer = Encoding.ASCII.GetBytes(x509.CreateX509SoapEnvelope());
PostData.Write(buffer, 0, buffer.Length); // error here
XmlDictionaryWriter xmlwriter = XmlDictionaryWriter.CreateTextWriter(PostData, Encoding.ASCII);
request.Headers.WriteHeaderContents(0,xmlwriter);

FYI, the output of x509.CreateX509SoapEnvelope() is a string and I tested that part and it works. I marked the code above to show where the error occurs.Need assistance with the error and how to fix it ?

Kev
  • 118,037
  • 53
  • 300
  • 385
wcfvemi
  • 159
  • 1
  • 4
  • 10
  • 1
    Is that the entire code block? You declared `Stream PostData` but didn't construct it into anything, so it's just sitting around as `null`. When you do `.Write` against it you will get a null reference exception. – debracey Aug 21 '11 at 22:00
  • XmlDictionaryWriter.CreateTextWriter accepts a stream type hence my need to convert my string value to a stream and then pass if as an argument when XMLDictionaryWriter is instantiated. Is there a better way of reworking my code ? – wcfvemi Aug 21 '11 at 23:46

3 Answers3

5

You never assigned a value to PostData. Thus, its default value is null and the compiler is smart enough to tell you this is a bad thing to do (if it permitted your code as is, you will get a runtime NullReferenceException). You need to instantiate an instance of a class that is a Stream (Stream is abstract and so you need a concrete instance) and assign it to PostData.

jason
  • 236,483
  • 35
  • 423
  • 525
  • My plan is to take the string output and pass it as an argument to the WriteHeaderContents method which either accepts a XMLDictionaryWrite or XMLWriter type .. is there a better way of doing it ? – wcfvemi Aug 21 '11 at 23:48
3

You have declared PostData, but not initialised it.

You need to have:

Stream PostData = new StreamWriter(filename);

at the bare minimum. See the MSDN documentation for more information on the various initialisers.

ChrisF
  • 134,786
  • 31
  • 255
  • 325
  • I do not have a filename to specify.. but I need to write the contents of "string" output to the Stream. How do I instantiate to accomodate this scenario ? – wcfvemi Aug 21 '11 at 23:42
0

I think I was after the same thing you are. I used a MemoryStream which didn't need a file in order to instantiate. See reference below:

MemoryStream

Nathan Pond
  • 336
  • 3
  • 5