Reading content from a file stream c# - c#

I have a web api service that accepts file uploads. The content of the file is a small JSON string like the following:
{ "name":"John", "age":31, "city":"New York" }
How do I get the file content while it is a stream instead of having to save the stream as a file on the web server and then open the file?
The following is my snippet:
byte[] fileData = null;
using(var binaryReader = new BinaryReader(httpRequest.Files[0].InputStream))
{
fileData = binaryReader.ReadBytes(httpRequest.Files[0].ContentLength);
}
I'm using the 4.0 .NET Framework

You can use a StreamReader class. Try this code:
using (var reader = new StreamReader(httpRequest.Files[0].InputStream))
{
var content = reader.ReadToEnd();
var json = JObject.Parse(content);
var name = json["name"];
}
Another option is to create a class for your json (manually or by http://json2csharp.com/):
public class Person
{
public string name { get; set; }
public int age { get; set; }
public string city { get; set; }
}
Then change your code to this:
using (var reader = new StreamReader(httpRequest.Files[0].InputStream))
{
var content = reader.ReadToEnd();
var person = JsonConvert.DeserializeObject<Person>(content);
var name = person.name;
}

Related

ASP .NET Core 3.1 IFormFile read a file from hosting

I would like to send a file from the hosting to the registered user with the confirmation email as an attachment.
My email sender class accepts Message model that contains public IFormFileCollection Attachments { get; set; }
My issue: I can not read the file from hosting and convert it to IFormFile.
This is a chunk of my code:
var pathToEmailAttachment = _webHostEnvironment.WebRootPath
+ Path.DirectorySeparatorChar.ToString()
+ "pdf"
+ Path.DirectorySeparatorChar.ToString()
+ "MyFile.pdf";
IFormFile file;
using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name));
}
var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });
await _emailSender.SendEmailAsync(message);
Message Model:
public class Message
{
public List<MailboxAddress> To { get; set; }
public string Subject { get; set; }
public string Content { get; set; }
public IFormFileCollection Attachments { get; set; }
public Message()
{
}
public Message(IEnumerable<string> to, string subject, string content, IFormFileCollection attachments)
{
To = new List<MailboxAddress>();
To.AddRange(to.Select(x => new MailboxAddress(x, x)));
Subject = subject;
Content = content;
Attachments = attachments;
}
}
Any advice or assistance would be greatly appreciated.
There might be 2 problems, incorrect FormFile instantiation and early closing of file stream. So you can try to fix FormFile creation with help of this answer and extend using statement
using (var stream = System.IO.File.OpenRead(pathToEmailAttachment))
{
file = new FormFile(stream, 0, stream.Length, null, Path.GetFileName(stream.Name))
{
Headers = new HeaderDictionary(),
ContentType = "you content type"
};
var message = new Message(new string[] { user.Email }, messageSubject, emailMessage, new FormFileCollection() { file });
await _emailSender.SendEmailAsync(message);
}

C# Reading XML from url while using XMLSerializer

I have been reading How To Parse XML In .NET Core There they show an example on parsing XML using XMLSerializer.
[XmlRoot("MyDocument", Namespace = "http://www.dotnetcoretutorials.com/namespace")]
public class MyDocument
{
public string MyProperty { get; set; }
public MyAttributeProperty MyAttributeProperty { get; set; }
[XmlArray]
[XmlArrayItem(ElementName = "MyListItem")]
public List MyList { get; set; }
}
public class MyAttributeProperty
{
[XmlAttribute("value")]
public int Value { get; set; }
}
and to read it:
using (var fileStream = File.Open("test.xml", FileMode.Open))
{
XmlSerializer serializer = new XmlSerializer(typeof(MyDocument));
var myDocument = (MyDocument)serializer.Deserialize(fileStream);
Console.WriteLine($"My Property : {myDocument.MyProperty}");
Console.WriteLine($"My Attribute : {myDocument.MyAttributeProperty.Value}");
foreach(var item in myDocument.MyList)
{
Console.WriteLine(item);
}
}
In the code above itreads the local xml file:
using (var fileStream = File.Open("test.xml", FileMode.Open)).
I want to read an XML file from URL, and make use of XmlSerializer, how would I accomplish this?
Since you already have your XML parsing logic in place, all you need is to swap out the file reading for an HTTP request.
using (var client = new HttpClient())
{
var content = await client.GetStreamAsync("http://...");
XmlSerializer serializer = new XmlSerializer(typeof(MyDocument));
var myDocument = (MyDocument)serializer.Deserialize(new MemoryStream(content));
Console.WriteLine($"My Property : {myDocument.MyProperty}");
Console.WriteLine($"My Attribute : {myDocument.MyAttributeProperty.Value}");
foreach(var item in myDocument.MyList)
{
Console.WriteLine(item);
}
}

How can I convert Serialized stream to a string?

I need to serialize and deserialize a list and write it on a JSON file to use later.
I successfully desirialize the file but failed to write after serialization. How can I do that?
Here is the code I have written.
StorageFile savedFile = await storageFolder.GetFileAsync("SavedData.json");
string text = await FileIO.ReadTextAsync(savedFile);
var serializer = new DataContractJsonSerializer(typeof(DataFormat));
var ms = new MemoryStream(Encoding.UTF8.GetBytes(text));
List<DataFormat> data = (List<DataFormat>)serializer.ReadObject(ms);
if (data == null)
{
data = new List<DataFormat>();
}
data.Add(new DataFormat
{
firstName = fnbox.Text,
lastName = lnbox.Text,
country = cbox.Text
});
MemoryStream stream = new MemoryStream();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataFormat));
ser.WriteObject(stream, data);
DataFormat Class -
[DataContract]
public class DataFormat : IEquatable<DataFormat>
{
[DataMember]
public string firstName{ get; set; }
[DataMember]
public string lastName { get; set; }
[DataMember]
public string country { get; set; }
public bool Equals(DataFormat other)
{
if (other == null)
{
return false;
}
return (firstName.Equals(other.firstName));
}
}
Additionally If there is any way to just add lines into an existing
file without replacing all the text, please let me know.
See if the following code is what you need. I'm not so sure whether you mean you don't understand how to write to stream.
private async void Button_Click(object sender, RoutedEventArgs e)
{
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
Windows.Storage.StorageFile sampleFile =await storageFolder.GetFileAsync("sample.json");
DataFormat data = new DataFormat();
data.firstName = "Barry";
data.lastName = "Wang";
data.country = "China";
Stream mystream = await sampleFile.OpenStreamForWriteAsync();
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DataFormat));
ser.WriteObject(mystream, data);
}
Here what you need, you can use LosFormatter class - see
https://weblog.west-wind.com/posts/2006/Oct/13/LosFormatter-for-easy-Serialization

Object to base 64 JSON file

I have an object T. I need to send the file representation of it into a web service. Without saving the file to a temp file.
WebService method:
myClient.SendFile(
new SendFileData{
id = "1",
fileName = "Foo",
fileType = "json",
fileContent = base64, // string Base64 variable here
}
To get the Base64 of a file I use :
public static string FileToBase64(string path) => FileToBase64(File.ReadAllBytes(path));
public static string FileToBase64(Byte[] bytes) => Convert.ToBase64String(bytes);
I have made those method to work on a temp file stored in a directory. saving the Json to file using :
using (StreamWriter file = File.CreateText(tempPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, _data);
}
And reading it like:
Directory.GetFiles(directory).Where().Select(x=> new {
fi = new FileInfo(f),
name = Path.GetFileNameWithoutExtension(f),
ext = Path.GetExtension(f).Trim('.'),
content = FileBase64Helper.FileToBase64(f)
})
I try to make a in memory file and convert it to b64 like:
public void Demo()
{
var myObject = new CustomType { Id = 1, Label = "Initialisation of a custom object" };
var stringRepresentation =
JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { });
SendFileData dataProjection = new SendFileData { };
var result = FakeClient.SendFile(dataProjection);
}
public class CustomType
{
public string Label { get; set; }
public int Id { get; set; }
}
public static class FakeClient
{
public static bool SendFile(SendFileData data) => true;
}
public class SendFileData
{
public string id { get; set; }
public string fileName { get; set; }
public string fileType { get; set; }
public string fileContent { get; set; }
}
Comparaison between direct convertion and FileReadByte:
var myObject = new CustomType { Id = 1, Label = "Initialisation of a custom object" };
var stringRepresentation = JsonConvert.SerializeObject(myObject, Formatting.Indented, new JsonSerializerSettings { });
var directSerialization = Convert.ToBase64String(Encoding.UTF8.GetBytes(stringRepresentation));
var tempPath = #"test.json";
using (StreamWriter file = File.CreateText(tempPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, myObject);
}
var fromFile = FileBase64Helper.FileToBase64(tempPath);
SendFileData dataProjection = new SendFileData { };
var result = FakeClient.SendFile(dataProjection);
Direct serialization:
ew0KICAiTGFiZWwiOiAiSW5pdGlhbGlzYXRpb24gb2YgYSBjdXN0b20gb2JqZWN0IiwNCiAgIklkIjogMQ0KfQ==
From file
eyJMYWJlbCI6IkluaXRpYWxpc2F0aW9uIG9mIGEgY3VzdG9tIG9iamVjdCIsIklkIjoxfQ==
If you're question is as follows and if i understand it correctly:
"Does File.ReadAllBytes add additional information about the file in it's return value, or is the return value equal to just having the content of the file as a byte array?"
Answer:
According to Microsoft Documentation, it will return the content of the file as a byte array.
Hope this helps!
Source: https://learn.microsoft.com/en-us/dotnet/api/system.io.file.readallbytes?view=netframework-4.7.2
EDIT: Decoding the base64, i found this:
The difference in the base64 encoded values is the json formatting, nothing else :D
Direct serialization:
From file:

How to write json format in C# string?

How i cab write a json format in C# string:
using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
{
string strNJson = #"{to:'topics/extrafx',notification:{title:{0},text:{1},sound: 'default'}}";
strNJson = string.Format(strNJson, not_title, not_body);
streamWriter.Write(strNJson);
streamWriter.Flush();
}
Please advice?
Json is the text serialisation of an object. So you simply have to create an object with those property and serialise it. To assit in creating the class that represent your object you can simply paste a Valid Json to Json 2 C#.
public class Notification
{
public string title { get; set; }
public string text { get; set; }
public string sound { get; set; }
}
public class RootObject
{
public string to { get; set; }
public Notification notification { get; set; }
}
And use it like :
var item = new RootObject {
to = "topics/extrafx",
notification = new Notification {
title = variableFoo,
text = variableBar,
sound = "default"
}
};
var result = JsonConvert.SerializeObject(item);
Try this version:
string not_title, not_body;
not_title = "title";
not_body = "body";
string strNJson = #"{{'to':'topics/extrafx','notification':{{'title':'{0}','text':'{1}','sound': 'default'}}}}";
strNJson = string.Format(strNJson, not_title, not_body);
private const string DATA = #"{
""uuid"": ""27c0f81c-23bc-4878-a6a5-49da58cd30dr"",
""status"": ""Work"",
""job_address"": ""Somewhere"",
""job_description"": ""Just a Test API CALL, John Mckinley's Job""}";
"" Calling the Data to this one
content = new StringContent(DATA, Encoding.UTF8, "application/json");
You can try this.

Categories

Resources