CryptographicBuffer.ConvertStringToBinary outputs a string rather than "binary" - windows-runtime

I'm using this simple method to save a string:
public static async void SaveStringAsync(string stringData, string fileName)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile file = await localFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
IBuffer buffer = CryptographicBuffer.ConvertStringToBinary(stringData, BinaryStringEncoding.Utf8);
await FileIO.WriteBufferAsync(file, buffer);
}
When I open the saved file in notepad, I see the string in full glory. I was under the impression that saving as binary would mean that if I open the file in notepad, all I'll see is garbage and random characters.
I wanted to see some very light obfuscation for what I am saving even though it is not a security requirement (no passwords, sensitive data being saved of any kind). Is there no way to write out a file that will show nonsense rather than a pure string?

Related

Dart CSV Writing

Hey so I haven't really messed around with it too much, but I was wondering if there was actually a way (before I go down a neverending rabbit hole) to read and write to CSV files in Dart/Flutter? I need to write to the files, not necessarily read them, and I'm willing to go to quite extreme lengths to do so. Any library works, built-in functions are even better. Any and all help is appreciated!
Use package csv from https://pub.dartlang.org/packages/csv
If you have a List<List<dynamic>> items that needs to convert into csv,
String csv = const ListToCsvConverter().convert(yourListOfLists);
If you want to write the csv to a file,
/// Write to a file
final directory = await getApplicationDocumentsDirectory();
final pathOfTheFileToWrite = directory.path + "/myCsvFile.csv";
File file = await File(pathOfTheFileToWrite);
file.writeAsString(csv);
Also, if you want to read a csv file directly into list<list<dynamic>>
final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(UTF8.decoder).transform(csvCodec.decoder).toList();
According to new packages and guidelines(2019) use following code
package csvfrom https://pub.dartlang.org/packages/csv.
If you have a List<List<dynamic>> items that needs to convert into csv,
String csv = const ListToCsvConverter().convert(yourListOfLists);
Then you can write the string to a file using file operations.
file.writeAsString('$csv');
Also, if you want to read a csv file directly into list<list<dynamic>>
final input = new File('a/csv/file.txt').openRead();
final fields = await input.transform(utf8.decoder).transform(new CsvToListConverter()).toList();

How to replace special symbols in a binary?

I am trying to read a pdf from a URL, return it as a binary and replace some characters. This is working for plain text with the following code but if the pdf has any special symbols like Trademark, copyright etc then my webservice is unable to return the result. Can some one please help me how to achieve this. The output should definitely be a binary output :
String html="";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
InputStream in = new URL(jsonobj.getString("xBody")).openStream();
int reads = in.read();
while(reads != -1){
baos.write(reads);
reads = in.read();
}
html= baos.toString();
The method baos.toString() internally calls new String(buffer), which uses the default encoding (the encoding actually being used by your system, probably not UTF-8). Try to provide the encoding explicitly, as follows:
String html = new String(baos.toByteArray(), "UTF-8");

Utilities base64Encode versus base64Decode method

Why the base64Decode can't decode something just encoded by base64Encode?
function test_base64encoding_decoding() {
var file = DriveApp.getFileById("<google drive png file id>");
// Encode file bytes as a string
var base64EncodedBytes = Utilities.base64Encode(file.getBlob().getBytes(), Utilities.Charset.UTF_8);
// Decode string
var bytes = Utilities.base64Decode(base64EncodedBytes, Utilities.Charset.UTF_8);
// create new file
var blob = Utilities.newBlob(bytes, file.getMimeType(), file.getName() + ".copy.png");
file.getParents().next().createFile(blob);
}
This google app script retrieves bytes from an existing google drive source file and convert these bytes to a base64 encoded string (base64EncodedBytes). It then converts back the string as a normal bytes array and create a brand new file on the same folder.
Now if we look at the final result into Google Drive we can see the copied file (the one with the suffix ".copy.png") does not have the same size and gets corrupted.
What's wrong with this encode/decode API usage?
Encode the file without the Charset. The charset makes sense when you are encoding strings, but in the case of a file ( like in this case) you should encode it and decode as something "general".
Try:
Utilities.base64Encode(file.getBlob().getBytes());
and
Utilities.base64Decode(base64EncodedBytes);
to see if it works for you.

Append data to existing file in Windows Store 8 using JSON

I have created an application in which I am inserting data to the file. It is working fine. Following is my code:
private async void btnSearch_Click(object sender, RoutedEventArgs e)
{
UserDetails details = new UserDetails
{
Name= TxtName.Text,
Course= TxtCouse.Text,
City=TxtCity.Text
};
string jsonContents = JsonConvert.SerializeObject(details);
StorageFolder localFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("Storage", CreationCollisionOption.ReplaceExisting); ;
StorageFile textFile = await localFolder.CreateFileAsync("UserDetails.txt", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream textStream = await textFile.OpenAsync(FileAccessMode.ReadWrite))
{
// write the JSON string!
using (DataWriter textWriter = new DataWriter(textStream))
{
textWriter.WriteString(jsonContents);
await textWriter.StoreAsync();
}
}
this.Frame.Navigate(typeof(BlankPage1));
}
Now I want that, when a user enter new data the data will append to the same existing file.
Appending data to a JSON text file would mean doing some parsing of the file to find the correct location to insert the text. That is, because JSON is structured with {} delimiters, it's not a simple matter of just appending text to the end of the file.
Given that your data doesn't look that large, the easiest thing to do is to deserialize the JSON from the existing file into memory, add your additional properties to that data structure, and then serialize back to JSON. In that case you probably just want to maintain the structure in memory during the app session, and just overwrite the file with new data whenever you need to. But of course you could also reopen the file, read/parse the JSON into memory, and then rewrite the contents.

How to read a text file with other encoding than UFT8 or UTF16 in WinRT?

If I read a textfile using FileIO.ReadTextAsync, ReadLinesAsync or a DataReader, I can only specify a member of the UnicodeEncoding enum for the encoding. This includes for some reason only Utf8, Utf16BE and Utf16LE. How can I read a text file with another encoding (like Windows-1252 or even regular Unicode (with 2 Bytes for all characters)) then?
This may be important if Windows Store Apps share text files with Desktop applications or read text files from the internet.
Hans' comment actually gave the answer to my question. Sample for Windows-1252:
string filePath = ...
StorageFile file = await StorageFile.GetFileFromPathAsync(filePath);
IBuffer buffer = await FileIO.ReadBufferAsync(file);
byte[] fileData = buffer.ToArray();
Encoding encoding = Encoding.GetEncoding("Windows-1252");
string text = encoding.GetString(fileData, 0, fileData.Length);
#JürgenBayer buffer.ToArray() wasn't available for me.
So, instead of writing:
string text = await FileIO.ReadTextAsync(file);
I wrote:
IBuffer buffer = await FileIO.ReadBufferAsync(file);
byte[] fileData;
CryptographicBuffer.CopyToByteArray(buffer, out fileData);
Encoding encoding = Encoding.GetEncoding("Windows-1252");
string text = encoding.GetString(fileData, 0, fileData.Length);