注意Stream.Seek,如果想要重复使用Stream,注意用Seek复位

Stream.Seek

sets the position within the current stream.

今天在做一个XML转换的时候怎么也取不到返回值,真是火大,Review了好几遍也没有发现问题,后来发现是对Stream重复操作,没有复位操作

 

XmlTextWriter writer = new XmlTextWriter(Console.Out);

xslt.Transform(reader, xslArg, writer, null);



MemoryStream retStream=new MemoryStream(4096);

XmlTextWriter writerOut = new XmlTextWriter(retStream,null);

//复位操作,重新加载XmlReader

stream.Seek(0, SeekOrigin.Begin); reader = XmlReader.Create(stream);

//----

xslt.Transform(reader, xslArg, writerOut);



IBaseMessageFactory factory = new BaseMessageFactory();

IBaseMessagePart part = factory.CreateMessagePart();

part.Data = retStream;

IBaseMessage retMsg = factory.CreateMessage();

retMsg.AddPart("body", part, true);

当时只能够在Console里看到Transform的信息,但是MemoryStream中一直没有东西,后来把Transform到Console关掉,发现MemoryStream里面有东西了,恍然大悟,原来是重复使用了Stream,没有复位

想想在BizTalk Adapter开发时候特别强调了对了流操作要注意Seek(0,SeekOrigin.Begin)复位操作,因为用过一次后,流的偏移offset已经到中间或者结尾了,如果要重新使用流,必须要复位操作,把流的偏移调整到0位.

 

ps:后续操作

  FileStream fsSend = File.Create(sendFile,2048);

  Stream stream = retMessage.BodyPart.Data;

  stream.Seek(0,SeekOrigin.Begin);

            

  byte[] buffer=new byte[4096];

  long bytesToRead = stream.Position;

  int bytesRead;

  while (0!=(bytesRead=stream.Read(buffer,0,buffer.Length)))

  {                

     fsSend.Write(buffer, 0, bytesRead);              

  }



  fsSend.Flush();

你可能感兴趣的:(Stream)