Where is temporary folder in IsolatedStorage (Windows Phone)? - windows-phone-7

I can not find where is temporary folder to add temp file into.
How do i find?

You just create your own folder and manage the content:
private void SaveTempFile(string fileName, object data)
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.DirectoryExists("temp") == false)
storage.CreateDirectory("temp");
fileName = Path.Combine("temp", fileName);
using (var fileStream = new IsolatedStorageFileStream(fileName, FileMode.Create, storage))
{
//Write the data
using (var isoFileWriter = new StreamWriter(fileStream))
{
// write your data in the format of your choice
}
}
}
Delete the file whenever you want to
public void DeleteTempFile(string fileName)
{
try
{
var storage = IsolatedStorageFile.GetUserStoreForApplication();
if (storage.DirectoryExists("temp") == false) return;
fileName = Path.Combine("temp", fileName);
if (storage.FileExists(fileName))
{
storage.DeleteFile(fileName);
}
}
catch (Exception) { }
}

There is no that kind of folder prepared for app on Windows Phone. You have to create it on your own and manage clearing the content form there when it's no longer needed. However you don't need to bother about deleting that files when your app is uninstalled - whole application folder is deleted from isolated storage then.

Related

Xamarin: Saving files to external storage on Android with an API level >=29

I'm trying to export files to the public external storage of an Android phone in Xamarin, for a backup DB. However, in the last version of Android phones (11.0 - API30), one can't opt-out of scoped storage using the property android:requestLegacyExternalStorage="true" of the <application> tag in the manifest.xml.
I made sure that the permissions READ_EXTERNAL_STORAGE & WRITE_EXTERNAL_STORAGE are granted before trying to create the file. Still, when trying to create a file, a System.UnauthorizedAccessException exception is thrown.
/* file 1: */
// ....
private async void Export_Tapped (object sender, EventArgs e) {
// check if permission for writing in external storage is given
bool canWrite = await FileSystem.ExternalStoragePermission_IsGranted ();
if (!canWrite) {
// request permission
canWrite = await FileSystem.ExternalStoragePermission_Request ();
if (!canWrite) {
// alert user
return;
}
}
// find the directory to export the db to, based on the platform
string fileName = "backup-" + DateTime.Now.ToString ("yyMMddThh:mm:ss") + ".db3";
string directory = FileSystem.GetDirectoryForDatabaseExport (); // returns "/storage/emulated/0/Download"
string fullPath = Path.Combine (directory, fileName);
// copy db to the directory
bool copied = false;
if (directory != null)
copied = DBConnection.CopyDatabase (fullPath);
if (copied)
// alert user
else
// alert user
}
// ....
/* file 2: */
class DBConnection
{
private readonly string dbPath;
// ....
public bool CopyDatabase(string path)
{
byte[] dbFile = File.ReadAllBytes(dbPath);
File.WriteAllBytes(path, dbFile); // --> this is where the exception is thrown <--
return true;
}
// ....
}
So the question stands: how does one write a new file to the public external storage of an Android device with an API level of 29 or more?
All the resources I have found so far, maybe you can gather more information than I did:
https://forums.xamarin.com/discussion/179999/access-denied-to-external-storage
(regarding private external storage) https://forums.xamarin.com/discussion/171039/saving-files-to-external-storage
https://learn.microsoft.com/en-us/xamarin/android/platform/files/external-storage?tabs=windows
https://developer.android.com/about/versions/11/privacy/storage#permissions
Try This , I use a dependency service to call this method in Native Android and save files like docx and pdf from their by byte array.
public async Task<bool> CreateFile(string fileName, byte[] docBytes, string fileType)
{
try
{
Java.IO.File file = new Java.IO.File(Android.OS.Environment.GetExternalStoragePublicDirectory(Android.OS.Environment.DirectoryDownloads).AbsolutePath, fileName + fileType);
OutputStream os = new FileOutputStream(file);
os.Write(docBytes);
os.Close();
}
catch
{
return false;
}
return true;
}
The path you use is incorrect, please try the following file path .
Context context = Android.App.Application.Context;
var filePath = context.GetExternalFilesDir(Android.OS.Environment.DirectoryDocuments);
Refer to https://forums.xamarin.com/discussion/comment/422501/#Comment_422501 .

directory in isolated storage windows phone

i would like to create a directory in my isoalted storage and a subdirectory in this directory
i use this method
private void create_directory(string directoryName)
{
try
{
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (!myIsolatedStorage.DirectoryExists(directoryName))
{
myIsolatedStorage.CreateDirectory(directoryName);
myIsolatedStorage.CreateDirectory(directoryName+"/Books");
myIsolatedStorage.CreateDirectory(directoryName + "/EpubBooks");
}
}
catch (Exception ex)
{
// handle the exception
}
}
but when i open the isolated storage explorer i Watch only the directory the two subdirectory are not created
Try to iterate the isolated storage with code. Your subdirs are created:
private void TestDir(string directoryName)
{
var list = new List<string>();
try
{
var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (myIsolatedStorage.DirectoryExists(directoryName))
{
var path = string.Format("{0}\\*", directoryName);
list = myIsolatedStorage.GetDirectoryNames(path).ToList();
}
}
catch
{
}
}
Looks like there is a bug in Isolated Storage Explorer (see the first comment).

storing a project folder in isolated storage

I am creating a windows phone project with static html files in a folder called "webapplication". i want to store all contents of "webapplication" folder in the isolated storage. Can some one help to resolve this?
Check out windows phone geek at http://windowsphonegeek.com/tips/all-about-wp7-isolated-storage-files-and-folders for information on Isolated Storage.
To create a folder do the following:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
myIsolatedStorage.CreateDirectory("NewFolder");
If you want to create a file inside the folder then:
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("NewFolder\\SomeFile.txt", FileMode.CreateNew, myIsolatedStorage));
If you are looking to copy the files to IsolatedStorage, then you need to run the following code the 1st time your application executes:
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] files = System.IO.Directory.GetFiles(folderPath);
foreach (var _fileName in files)
{
if (!storage.FileExists(_fileName))
{
string _filePath = _fileName;
StreamResourceInfo resource = Application.GetResourceStream(new Uri(_filePath, UriKind.Relative));
using (IsolatedStorageFileStream file = storage.CreateFile("NewFolder\\SomeFile.txt", FileMode.CreateNew, Storage))
{
int chunkSize = 102400;
byte[] bytes = new byte[chunkSize];
int byteCount;
while ((byteCount = resource.Stream.Read(bytes, 0, chunkSize)) > 0)
{
file.Write(bytes, 0, byteCount);
}
}
}
}
}

Export FileContentResult files to ZIP

I use C#-MVC3. I have an "export" page. I have some functions for exporting different tables from the DB, every function creates a CSV file from the table and returns a FileContentResult file to the user.
Now I want to create a button for "export all", to download all the files at once.
I tried to use ZipFile but it gets only file names and path - files that were saved on the server, not "FileContentResult" files.
So I wanted to save the "FileContentResult" files temporarily on the server, zip them and delete them - but I can't find how to save a "FileContentResult" file.
If you can help me or give me another idea, I'll glad to hear.
my solution:
public ZipFile DownloadAllToZip()
{
string path = "c:\\TempCSV";
try
{
if (Directory.Exists(path))
{
EmptyFolder(path);
}
else
{
DirectoryInfo di = Directory.CreateDirectory(path);
}
List<FileContentResult> filesToExport = GetAllCSVs();
foreach (var file in filesToExport)
{
try
{
using (FileStream stream = new FileStream(path + "\\" + file.FileDownloadName, FileMode.CreateNew))
{
using (StreamWriter writer = new StreamWriter(stream, Encoding.UTF8))
{
byte[] buffer = file.FileContents;
stream.Write(buffer, 0, buffer.Length);
writer.Close();
}
}
}
catch { }
}
}
catch{ }
Response.Clear();
Response.BufferOutput = false;
Response.ContentType = "application/zip";
Response.AddHeader("content-disposition", "attachment; filename=MaterialAssetTracker.zip");
ZipFile zip= new ZipFile();
using (zip)
{
zip.CompressionLevel = CompressionLevel.None;
zip.AddSelectedFiles("*.csv", path + "\\", "", false);
zip.Save(Response.OutputStream);
}
Response.Close();
EmptyFolder(path);
return zip;
}

WP7: Delete IsolatedStorageFile

I would really appreciate some help with deleting a file from IsolatedStorage on WP7. I am basically downloading a file from the web, storing it in Isolated Storage and then uploading it to my Downloads folder in my Dropbox. Once I have uploaded it, I would like to delete the file from Isolated Storage, but am getting Exception errors when trying to do so.
Here is my code :
public void readCompleteCallback(Object sender, OpenReadCompletedEventArgs e)
{
if (e.Error == null)
{
try
{
//string fileName = txtUrl.Text.Substring(txtUrl.Text.LastIndexOf("/") + 1).Trim();
string fileName = searchBox.Text + fileExt;
//string fileName = "DownloadedNZB.nzb";
bool isSpaceAvailable = IsSpaceIsAvailable(e.Result.Length);
if (isSpaceAvailable)
{
// Save mp3 to Isolated Storage
using (var isfs = new IsolatedStorageFileStream(fileName,
FileMode.CreateNew,
IsolatedStorageFile.GetUserStoreForApplication()))
{
long fileLen = e.Result.Length;
byte[] b = new byte[fileLen];
var numberOfBytesRead = e.Result.Read(b, 0, b.Length);
isfs.Write(b, 0, numberOfBytesRead);
isfs.Flush();
isfs.Close();
isf = IsolatedStorageFile.GetUserStoreForApplication();
stream = isf.OpenFile(fileName, FileMode.Open);
MessageBox.Show("File downloaded successfully");
App.GlobalClient.UploadFileAsync("/Public/", fileName, stream, (response) =>
{
MessageBox.Show("Uploaded file to Dropbox OK.");
},
(error) =>
{
MessageBox.Show(error + "Cannot upload file to dropbox.");
});
}
//stream.Close();
isf.DeleteFile(searchBox.Text + fileExt);
}
else
{
MessageBox.Show("Not enough to space available to download the file");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
else
{
MessageBox.Show(e.Error.Message);
}
}
I cannot think where I am going wrong, but if someone could point me in the right direction, I would appreciate it.
You are trying to delete file inside using statement, where file is not closed yet
UPD: Your upload is async, so you can delete file only when it completed. Put your code near MessageBox.Show("Uploaded file to Dropbox OK.");

Resources