Mon problème fondamental est que lorsque vous usingappelez Disposea StreamWriter, il élimine également le BaseStream(même problème avec Close).
J'ai une solution de contournement pour cela, mais comme vous pouvez le voir, cela implique de copier le flux. Existe-t-il un moyen de le faire sans copier le flux?
Le but de ceci est d'obtenir le contenu d'une chaîne (initialement lue à partir d'une base de données) dans un flux, afin que le flux puisse être lu par un composant tiers.
NB : je ne peux pas modifier le composant tiers.
public System.IO.Stream CreateStream(string value)
{
var baseStream = new System.IO.MemoryStream();
var baseCopy = new System.IO.MemoryStream();
using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
{
writer.Write(value);
writer.Flush();
baseStream.WriteTo(baseCopy);
}
baseCopy.Seek(0, System.IO.SeekOrigin.Begin);
return baseCopy;
}
Utilisé comme
public void Noddy()
{
System.IO.Stream myStream = CreateStream("The contents of this string are unimportant");
My3rdPartyComponent.ReadFromStream(myStream);
}
Idéalement, je recherche une méthode imaginaire appelée BreakAssociationWithBaseStream, par exemple
public System.IO.Stream CreateStream_Alternate(string value)
{
var baseStream = new System.IO.MemoryStream();
using (var writer = new System.IO.StreamWriter(baseStream, System.Text.Encoding.UTF8))
{
writer.Write(value);
writer.Flush();
writer.BreakAssociationWithBaseStream();
}
return baseStream;
}