I am working on a feature that can take xmlstring as an input and uploads it to the server. Below is the code I'm playing around but I saw some answers in the other places suggesting System.io.stream. So, I'm curious about that way of doing it. How can I just store the .xml on the server with/without saving it on the disk.
Code for using file on the Base Directory folder location
string filename = "Sample.XML";
List<string> file = new();
file.Add(filename);
//Downloading XML string using web client
string Xml = _webClientService.DownloadXml("http://aws.api/Links?=admin");
string fileLocation = AppDomain.CurrentDomain.BaseDirectory + "\\SampleFiles";
if (!Directory.Exists(fileLocation)) { Directory.CreateDirectory(fileLocation); }
XmlReader reader = XmlReader.Create(Xml);
XDocument doc = XDocument.Load(reader);
doc.Save(fileLocation + $"\\{file}");
I'm yet to work on the upload piece. But the method declaration would look like:
UploadFiles(string filelocation, List<string> fileNames);
2nd method using System.io.stream
Stream s = _httpService.GetStream("http://aws.api/Links?=admin");
var file = "sample.gz";
Stream gZip = new GZipStream(s, CompressionMode.Decompress);
XmlReader reader = XmlReader.Create(gZip, new XmlReaderSettings { ConformanceLevel = ConformanceLevel.Fragment });
reader.MoveToContent();
XDocument doc = XDocument.Load(reader);
And for this one, the prototype can be like:
UploadFileStream(string file, Stream strm);
Code for GetStream:
public static async Task<Stream> GetStream(string url)
{
var t = Task.Run(() => httpClient.GetAsync(url));
t.Wait();
HttpResponseMessage response = t.Result;
Stream res;
// Handle the response
switch (response.StatusCode)
{
case HttpStatusCode.OK:
res = await response.Content.ReadAsStreamAsync();
break;
default:
int statusCode = (int)response.StatusCode;
throw new HttpException(statusCode, response.ReasonPhrase);
}
return res;
}
Is it possible to avoid gZip conversion & store xmlfile direct to server using the memory stream?