我有一个对象T。我需要将其文件表示形式发送到Web服务中。无需将文件保存为临时文件。
WebService方法:
myClient.SendFile(
new SendFileData{
id = "1",
fileName = "Foo",
fileType = "json",
fileContent = base64, // string Base64 variable here
}
要获取文件的Base64,请使用:
public static string FileToBase64(string path) => FileToBase64(File.ReadAllBytes(path));
public static string FileToBase64(Byte[] bytes) => Convert.ToBase64String(bytes);
我已经做出了那些方法来处理存储在目录中的临时文件。使用以下命令将Json保存到文件:
using (StreamWriter file = File.CreateText(tempPath))
{
JsonSerializer serializer = new JsonSerializer();
serializer.Serialize(file, _data);
}
阅读方式如下:
Directory.GetFiles(directory).Where().Select(x=> new {
fi = new FileInfo(f),
name = Path.GetFileNameWithoutExtension(f),
ext = Path.GetExtension(f).Trim('.'),
content = FileBase64Helper.FileToBase64(f)
})
我尝试制作一个内存文件,并将其转换为b64,如:
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; }
}
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);
直接序列化:
ew0KICAiTGFiZWwiOiAiSW5pdGlhbGlzYXRpb24gb2YgYSBjdXN0b20gb2JqZWN0IiwNCiAgIklkIjogMQ0KfQ ==
来自文件
eyJMYWJlbCI6IkluaXRpYWxpc2F0aW9uIG9mIGEgY3VzdG9tIG9iamVjdCIsIklkIjoxfQ ==
答案 0 :(得分:0)
如果您的问题如下,并且我理解正确:
“ File.ReadAllBytes是否在文件的返回值中添加有关文件的其他信息,或者返回值等于仅将文件的内容作为字节数组?”
答案:
根据Microsoft文档,它将以字节数组形式返回文件的内容。
希望这会有所帮助!
来源:https://docs.microsoft.com/en-us/dotnet/api/system.io.file.readallbytes?view=netframework-4.7.2
编辑:解码base64,我发现: base64编码值的区别是json格式,仅此而已:D
直接序列化:
来自文件: