Save file to device with memorystream - file

I was wondering if it is possible with xamarin.forms to download any type of file to the device.. de files are stored on Azure, i get a Memorystream of the file, its very important for my app. my question excists of 2 parts actually,
how to download de file to the device of the user?,
and how to show the file of Any type in a default application of the type ( like pdf reader)
this is what i tried
MemoryStream memoryStream = AzureDownloader.DownloadFromAzureBlobStorage(null, doc.azure_container, doc.file_path, ref filen, true);
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
string localFilename = doc.filename;
string localPath = Path.Combine(documentsPath, localFilename);
File.WriteAllBytes(localPath, memoryStream.ToArray()); // this is a try to save to local storage
any help appreciated

how to download the file to the device of the user?
Use PCLStorage as its cross-platform and would work for iOS and Android:
public async Task CreateRealFileAsync()
{
// get hold of the file system
IFolder rootFolder = FileSystem.Current.LocalStorage;
// create a folder, if one does not exist already
IFolder folder = await rootFolder.CreateFolderAsync("MySubFolder", CreationCollisionOption.OpenIfExists);
// create a file, overwriting any existing file
IFile file = await folder.CreateFileAsync("MyFile.txt", CreationCollisionOption.ReplaceExisting);
// populate the file with some text
await file.WriteAllTextAsync("Sample Text...");
}
how to show the file of Any type in a default application of the type
( like pdf reader)
this is too broad and could have several solutions depending on what exactly you want to achieve.
Hope this helps

Related

UWP how to get access to file in folder

Help me please, I can't get access to file which I choose by FileOpenPicker.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();
using (FileStream fs = new FileStream(file.Path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
}
What is wrong?
Because of how UWP sandboxes access to the filesystem, you can't construct a FileStream directly from a StorageFile's path. Instead, you have a few options, in order from simplest to most complex:
1) If your file is small enough, you can just use the helpers in the FileIO static class to read it all at once:
string text = await FileIO.ReadTextAsync(file); // or ReadLinesAsync or ReadBufferAsync, depending on what you need
2) Use the OpenAsync() method on StorageFile:
using (IRandomAccessStream stream = await file.OpenAsync(FileAccessMode.Read, StorageOpenOptions.AllowReadersAndWriters))
{
// your reading code here
}
If you need to, you can convert between IRandomAccessStream and .NET Streams with the AsStream(), AsStreamForRead() and AsStreamForWrite() extension methods on IRandomAccessStream, the docs for which are here.
3) If you want complete control, you can get a SafeFileHandle to the underlying file using CreateSafeFileHandle(), like so:
SafeFileHandle fileHandle = file.CreateSafeFileHandle(FileAccess.Read, FileShare.ReadWrite);
You can then use this file handle to create a standard FileStream:
using (FileStream fs = new FileStream(fileHandle, FileAccess.Read))
{
// Read stuff here
}
This is the only way to reliably use a FileStream on a UWP StorageFile, and should be used with some caution. The official docs have more details on the implications of doing this.
FileOpenPicker gives you a StorageFile which wraps the opened files and gives you permission to it. This doesn't give you access to the file in general - e.g. you cannot use its Path only to open it with a FileStream. Instead, you need to use the respective Windows.Storage APIs to do this. I usually use the OpenStreamForReadAsync extension method. Add using System.IO to the file header and then:
var stream = await file.OpenStreamForReadAsync();
This method returns a System.IO.Stream which you can use with classic System.IO-enabled APIs.
Please avoid use file Path to access file stream in UWP platform, if you have get the file with FileOpenPicker. You could get the file stream with following.
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.Thumbnail;
openPicker.SuggestedStartLocation = PickerLocationId.Desktop;
openPicker.CommitButtonText = "Открыть";
openPicker.FileTypeFilter.Add(".xlsx");
var file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
}
And if you need use stream in System.IO namespace. please call AsStream method for IRandomAccessStream object.
var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.Read);
System.IO.Stream iostream = stream.AsStream();
For more detail please refer this official document.

Writing from persistent data path to streaming asset

I'm trying to get bytes from Application.persistentDataPath to streaming asset and save it as an mp4 file but my code doesnt work.
Here it is :
IEnumerator streamit(){
string filePath ="file:///"+ Path.Combine(Application.persistentDataPath, "Locomotive Part 1.mp4");
Uri uri = new Uri(filePath);
string converted = uri.AbsoluteUri;
WWW www = new WWW(converted);
Debug.Log (www.error);
yield return www;
using (FileStream fs = new FileStream(Application.persistentDataPath+"/example.mp4", FileMode.Append))
foreach(byte data in www.bytes){
fs.WriteByte (data);
}
}
So what am I doing wrong ? Its not working on both IOS and Mac
Oh, I found my problem.
Everything that doesn't work because of empty spaces on the source path. In IOS, you have to change empty spaces with "%20" whenever you are sending a path.
Thanks Anyway !

Android studio how delete downloaded files parse?

I am new in android studio and I am using Parse to store images. I am creating an image gallery and I am able to display downloaded images from parse to gridview. The problem is everytime I restart the app, my SDcard will download the exact same files from Parse. Is there a way to delete these unnecessary files? Or how can I put these Downloaded image files into a temporary storage where they will be deleted once the user is finished with the app?
This is my code for downloading the images and store them in gridview:
for (ParseObject imageOb : objects) {
final ParseFile file = (ParseFile) imageOb.get("image");
file.getDataInBackground(new GetDataCallback() {
#Override
public void done(byte[] data, ParseException e) {
if (e == null) {
Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);
Uri uri = getImageUri(getApplicationContext(), bitmap);
File imageFiles = new File(getRealPathFromURI(uri));
imageAdapter.add(imageFiles.toString());
}
imageAdapter.notifyDataSetChanged();
}
});
}
There are some answers already on Stack overflow about temporary files, for example What is the best way to create temporary files
You could also manually delete the downloaded files when the application doesn't need them anymore. If you download them in onCreate you should delete them in onDestroy. Otherwise, check out this Article about the Android lifecycle

Titanium how to move DB to SD card

Im programming in Titanium for Android.
I have 6 sqlite databases and i don't want to store them on the device internal memory because DB amount size is too large.
So, how can i move the sqlite files to SD card programmatically? Or how to install Dbs directly on the SD card when users installs my App from PlayStore?
PD: I try adding "PreferExternal" but this didn't fix my problem.
<manifest android:installLocation="preferExternal</manifest>
thanks in advance!
From Titanium docs of Ti.Database.open.
Open a Database on External Storage (Android)
A database, with a filename of mydb2Installed and located at the absolute path provided, is opened.
if (Ti.Platform.name === 'android' && Ti.Filesystem.isExternalStoragePresent()) {
var db2 = Ti.Database.open(Ti.Filesystem.externalStorageDirectory + 'path' + Ti.Filesystem.separator + 'to' + Ti.Filesystem.separator + 'mydb2Installed');
}
Hopefully this will do the trick.
I have no idea about titanium. But in android you can move DB by below logic:
copy your Database.db file in your projects assets folder.
In manifest file define permission shown below:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
now using code copy database file from /asset to device's external storage
For copy file use below code,
try {
// Open your local db as the input stream
InputStream myInput = myContext.getAssets().open("your database file name");
// Path to the just created empty db
String outFileName = "path of external storage/<database_file_name>";
OutputStream myOutput = new FileOutputStream(outFileName);
// transfer bytes from the inputfile to the outputfile
byte[] buffer = new byte[1024];
int length;
while ((length = myInput.read(buffer)) > 0)
{
myOutput.write(buffer, 0, length);
}
// Close the streams
myOutput.flush();
myOutput.close();
myInput.close();
}
catch (Exception e)
{
Log.e("error", e.toString());
}
According to this question : Android: use SQLite database on SD Card (not using internal Android Data Store at all)
You can use :
SQLiteDatabase.openOrCreateDatabase(String, SQLiteDatabase.CursorFactory)
Put your path as the first parameter and null as the second.
To get the path of your sdcard do :
Environment.getExternalStorageDirectory();
But note that everyone with a physical access to the device can access to the database file...

Sharepoint 2010 Upload file using Silverlight 4.0

I am trying to do a file upload from Silverlight(Client Object Model) to Sharepoint 2010 library.. Please see the code below..
try{
context = new ClientContext("http://deepu-pc/");
web = context.Web;
context.Load(web);
OpenFileDialog oFileDialog = new OpenFileDialog();
oFileDialog.FilterIndex = 1;
oFileDialog.Multiselect = false;
if (oFileDialog.ShowDialog().Value == true)
{
var localFile = new FileCreationInformation();
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
localFile.Url = System.IO.Path.GetFileName(oFileDialog.File.Name);
List docs = web.Lists.GetByTitle("Gallery");
context.Load(docs);
File file = docs.RootFolder.Files.Add(localFile);
context.Load(file);
context.ExecuteQueryAsync(OnSiteLoadSuccess, OnSiteLoadFailure);
}
}
catch (Exception exp)
{
MessageBox.Show(exp.ToString());
}
But I am getting the following error
System.Security.SecurityException: File operation not permitted. Access to path '' is denied.
at System.IO.FileSecurityState.EnsureState()
at System.IO.FileSystemInfo.get_FullName()
at ImageUploadSilverlight.MainPage.FileUpload_Click(Object sender, RoutedEventArgs e)
Any help would be appreciated
Thanks
Deepu
Silverlight runs with very restricted access to the client user's filesystem. When using an open-file dialog, you can get the name of the selected file within its parent folder, the length of the file, and a stream from which to read the data in the file, but not much more than that. You can't read the full path of the file selected, and you are getting the exception because you are attempting to do precisely that.
If you want to read the entire content of the file into a byte array, you'll have to replace the line
localFile.Content = System.IO.File.ReadAllBytes(oFileDialog.File.FullName);
with something like
localFile.content = ReadFully(oFileDialog.File.OpenRead());
The ReadFully method reads the entire content of a stream into a byte array. It's not a standard Silverlight method; instead it
is taken from this answer. (I gave this method a quick test on Silverlight, and it appears to work.)

Resources