How delete file in localstorage on winrt? - c#

i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}

Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}

i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete

/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}

Related

In-App Purchase - application let me purchase again after navigate

i am triyng to add in-app purchase option for my application.
i can purchase product correctly but when i purchase and navigate to other page and back to purchase page i can still purchase same product again. and when i purchase another product, my older purchased product become unpurchased.
here is my codes:
Windows.Storage.ApplicationDataContainer localSettings = Windows.Storage.ApplicationData.Current.LocalSettings;
Windows.Storage.StorageFolder localFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
LicenseChangedEventHandler licenseChangeHandler = null;
public SatinAlma()
{
this.InitializeComponent();
}
private async Task LoadInAppPurchaseProxyFileAsync()
{
StorageFolder proxyDataFolder = await Package.Current.InstalledLocation.GetFolderAsync("Data");
StorageFile proxyFile = await proxyDataFolder.GetFileAsync("in-app-purchase.xml");
licenseChangeHandler = new LicenseChangedEventHandler(InAppPurchaseRefreshScenario);
CurrentAppSimulator.LicenseInformation.LicenseChanged += licenseChangeHandler;
await CurrentAppSimulator.ReloadSimulatorAsync(proxyFile);
try
{
ListingInformation listing = await CurrentAppSimulator.LoadListingInformationAsync();
var PurchasePzl9 = listing.ProductListings["puzzle9"];
var PurchasePzl16 = listing.ProductListings["puzzle16"];
var PurchasePzl25 = listing.ProductListings["puzzle25"];
var PurchaseYardimseverlik = listing.ProductListings["yardimseverlik"];
var PurchaseTumpaket = listing.ProductListings["tumpaket"];
}
catch (Exception)
{
OAL_toast.showToast("LoadListingInformationAsync API call failed\n");
}
}
///////**i insert and delete this part nothing changed
//protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
//{
// if (licenseChangeHandler != null)
// {
// CurrentAppSimulator.LicenseInformation.LicenseChanged -= licenseChangeHandler;
// }
// base.OnNavigatingFrom(e);
//}
protected override async void OnNavigatedTo(NavigationEventArgs e)
{
await LoadInAppPurchaseProxyFileAsync();
}
private void InAppPurchaseRefreshScenario()
{
}
private async void purchaseProduct()
{
LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
if (!licenseInformation.ProductLicenses[stringPurchaseProduct].IsActive)
{
try
{
await CurrentAppSimulator.RequestProductPurchaseAsync(stringPurchaseProduct);
if (licenseInformation.ProductLicenses[stringPurchaseProduct].IsActive)
{
OAL_toast.showToast(stringPurchaseProduct + " purchased.");
this.Frame.Navigate(typeof(MainPage));
}
else
{
//OptimeAnimationLib.MsgBox(stringPurchaseProduct + " was not purchased.");
OAL_toast.showToast(stringPurchaseProduct + " was not purchased.");
}
}
catch (Exception)
{
OAL_toast.showToast("Unable to buy " + stringPurchaseProduct);
}
}
else
{
OAL_toast.showToast("you already own " + stringPurchaseProduct);
}
}
private void IMG_puzzle9_PointerReleased(object sender, PointerRoutedEventArgs e)
{
LicenseInformation licenseInformation = CurrentAppSimulator.LicenseInformation;
var productLicense = licenseInformation.ProductLicenses["puzzle9"];
if (productLicense.IsActive)
{
OAL_toast.showToast("you already own Puzzle 9.");
}
else
{
stringPurchaseProduct = "puzzle9";
purchaseProduct();
}
}
thanks, sorry for my english
It looks like you're reloading your Store simulator XML file every time you navigate, which will reset any Store activity you've done previously. Change your code so that you load the XML only when the app starts, and then you should see the Store state maintain itself across navigations. Note also that when you restart the app you'll be reloading the XML and thus reset the state.

Exception while accessing 'FileOpenPicker' for the SecondTime in WindowsStoreApps

I want to open FileOpenPicker for two times one after the other.i.e)After selecting the image from FileOpenPicker for first time it returns back to the page with the selected image,that time a MessageDialog is shown,And clicking OK button on MessageDialog I am opening the FileOpenPicker again,this time I get a weird crash on
open.FileTypeFilter.Clear();
as 'Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))'.And My code is below.
private async void PickImage()
{
FileOpenPicker open = new FileOpenPicker();
open.SuggestedStartLocation = PickerLocationId.PicturesLibrary;
open.ViewMode = PickerViewMode.Thumbnail;
// Filter to include a sample subset of file types
open.FileTypeFilter.Clear();
open.FileTypeFilter.Add(".bmp");
open.FileTypeFilter.Add(".png");
open.FileTypeFilter.Add(".jpeg");
open.FileTypeFilter.Add(".jpg");
StorageFile file = await open.PickSingleFileAsync();
if (file != null)
{
if (prop1.Source == null)
{
Dialogpopup();
return;
}
else if (prop2.Source == null)
{
Dialogpopup();
return;
}
}
}
private async void Dialogpopup()
{
MessageDialog msgDialog = new MessageDialog("Would you like to add additional photos?");
UICommand okBtn = new UICommand("Yes");
okBtn.Invoked = OkBtnClick;
msgDialog.Commands.Add(okBtn);
UICommand cancelBtn = new UICommand("No");
cancelBtn.Invoked = CancelBtnClick;
msgDialog.Commands.Add(cancelBtn);
//Show message
msgDialog.ShowAsync();
}
private async void OkBtnClick(IUICommand command)
{
img_PointerPressed(img_galary, null);
}
private void img_PointerPressed(object sender, PointerRoutedEventArgs e)
{
if (sender == img_galary)
{
PickImage();
}
}

uploadfile windows form C# web service

i'm new here,
help me out here please,
i am working with web service and doing upload file.
here's my code for uploading file
private void Button_Click(object sender, RoutedEventArgs e)
{
testServiceClient = new TestServiceClient();
var uploadFile = "C:\\Computer1\\Sample.csv";
try
{
var dir = #"\\Computer2\UploadedFile\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadFile);
var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
client.Dispose();
MessageBox.Show("ok");
testServiceClient.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
i can upload file in the same network, but my question is this,
how can i upload file when the two computer is not in the same network?
i've tried changing the
var dir = #"\\Computer2\UploadedFile\";
to
var dir = #"https://Computer2/UploadedFile/";
but i'm getting an error 'unable to connect to remote server'
help me out here pls.
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://Computer2/UploadedFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadedFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.
This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service

Save Strokes of inkManager in localStorage - windows 8 app

well i try a lot of things but i don't really understand everything of save in localstorage. I know how its work since the camera, but i don't know how to make it with inkManager. If you're any ideas ?
This is my code to save where the user wants, but i would like to "auto-save" in localstorage :
private async void save_Button(object sender, RoutedEventArgs e)
{
if (_inkManager.GetStrokes().Count > 0)
{
try
{
Windows.Storage.Pickers.FileSavePicker save = new Windows.Storage.Pickers.FileSavePicker();
save.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
save.DefaultFileExtension = ".jpg";
save.FileTypeChoices.Add("JPG", new string[] { ".jpg" });
StorageFile filesave = await save.PickSaveFileAsync();
IOutputStream ab = await filesave.OpenAsync(FileAccessMode.ReadWrite);
if (ab != null)
await _inkManager.SaveAsync(ab);
// await save.CopyAsync(ApplicationData.Current.LocalFolder, "merge1.jpg");
if (save != null)
{
Clipboard.Source = new Windows.UI.Xaml.Media.Imaging.BitmapImage(new Uri("ms-appdata:///local/merge1.jpg"));
}
}
catch (Exception)
{
}
}
}
The solution is pretty easy finally :
StorageFile myMerge = await ApplicationData.Current.LocalFolder.CreateFileAsync("myimg.png");
IOutputStream ac = await myMerge.OpenAsync(FileAccessMode.ReadWrite);
if (ac != null)
await _inkManager.SaveAsync(ac);

How to download/open the file that I retrive by server path?

I am making a module that shows the tree view of documents that are stores on my drive in a folder. It is retrieving well. But the problem is that the documents are in different format like(.pdf, .docx etc). That are not opening in browser on click. There it shows a 404.4 error. So Tell me how can I download/open different format files through button click? The following is my code:
protected void Page_Load(System.Object sender, System.EventArgs e)
{
try
{
if (!Page.IsPostBack)
{
if (Settings["DirectoryPath"] != null)
{
BindDirectory(Settings["DirectoryPath"].ToString());
}
else
{
BindDirectory(Server.MapPath("~/"));
}
}
}
catch (DirectoryNotFoundException DNEx)
{
try
{
System.IO.Directory.CreateDirectory("XIBDir");
BindDirectory(Server.MapPath("XIBDir"));
}
catch (AccessViolationException AVEx)
{
Response.Write("<!--" + AVEx.Message + "-->");
}
}
catch (Exception exc) //Module failed to load
{
Exceptions.ProcessModuleLoadException(this, exc);
}
}
#endregion
#region Optional Interfaces
/// -----------------------------------------------------------------------------
/// <summary>
/// Registers the module actions required for interfacing with the portal framework
/// </summary>
/// <value></value>
/// <returns></returns>
/// <remarks></remarks>
/// <history>
/// </history>
/// -----------------------------------------------------------------------------
public ModuleActionCollection ModuleActions
{
get
{
ModuleActionCollection Actions = new ModuleActionCollection();
Actions.Add(this.GetNextActionID(), Localization.GetString(ModuleActionType.AddContent, this.LocalResourceFile), ModuleActionType.AddContent, "", "", this.EditUrl(), false, SecurityAccessLevel.Edit, true, false);
return Actions;
}
}
#endregion
private void BindDirectory(string Path)
{
try
{
System.IO.DirectoryInfo dirRoot = new System.IO.DirectoryInfo(Path);
TreeNode tnRoot = new TreeNode(Path);
tvDirectory.Nodes.Add(tnRoot);
BindSubDirectory(dirRoot, tnRoot);
tvDirectory.CollapseAll();
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnRoot = new TreeNode("Access Denied");
tvDirectory.Nodes.Add(tnRoot);
}
}
private void BindSubDirectory(System.IO.DirectoryInfo dirParent, TreeNode tnParent)
{
try
{
foreach (System.IO.DirectoryInfo dirChild in dirParent.GetDirectories())
{
//TreeNode tnChild = new TreeNode(dirChild.Name);
TreeNode tnChild = new TreeNode(dirChild.Name, dirChild.FullName);
tnParent.ChildNodes.Add(tnChild);
BindSubDirectory(dirChild, tnChild);
}
}
catch (UnauthorizedAccessException Ex)
{
TreeNode tnChild = new TreeNode("Access Denied");
tnParent.ChildNodes.Add(tnChild);
}
}
private void BindFiles(string Path)
{
try
{
tvFile.Nodes.Clear();
System.IO.DirectoryInfo dirFile = new System.IO.DirectoryInfo(Path);
foreach (System.IO.FileInfo fiFile in dirFile.GetFiles("*.*"))
{
string strFilePath = Server.MapPath(fiFile.Name);
string strFilePaths = "~/" + fiFile.FullName.Substring(15);
TreeNode tnFile = new TreeNode(fiFile.Name, fiFile.FullName, "", strFilePaths, "_blank");
tvFile.Nodes.Add(tnFile);
}
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
protected void tvDirectory_SelectedNodeChanged(object sender, EventArgs e)
{
try
{
string strFilePath = tvDirectory.SelectedNode.Value;
BindFiles(tvDirectory.SelectedNode.Value);
}
catch (Exception Ex)
{
Response.Write("<!--" + Ex.Message + "-->");
}
}
}
}
404.4 means that the web server (IIS presumably) does not now how to serve the file (based on extension). If your code is serving other files correctly, this is a web server configuration issue. Check your servers documentation for adding the appropriate handlers for the file extensions that aren't working.
I would use a hyperlink in your treeview that opens the link: openfile.ashx?path=[insertpathhere] (make sure that your link opens in target="_blank")
within your Generic Handler (ASHX) you have access to load a file from Disk, and stream its bytes into the responseStream. and that will cause the file to download at the browser. You should also set the content-type where applicable.
Code Sample Requested...
Preface: There are some "extra" things going on here... I base64 Encoded the path in my example because I didnt want the path to be 'human-readable'. Also, when I handed it off to the browser I am pre-pending 'export-' plus a timestamp... but you get the idea...
public class getfile : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var targetId = context.Request.QueryString["target"];
if (string.IsNullOrWhiteSpace(targetId))
{
context.Response.ContentType = "text/plain";
context.Response.Write("Fail: Target was expected in querystring.");
return;
}
try
{
var url = new String(Encoding.UTF8.GetChars(Convert.FromBase64String(targetId)));
var filename = url.Substring(url.LastIndexOf('\\') + 1);
filename = "export-" + DateTime.Now.ToString("yyyy-MM-dd-HHmm") + filename.Substring(filename.Length - 4);
context.Response.ContentType = "application/octet-stream";
context.Response.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", filename));
var data = File.ReadAllBytes(url);
File.Delete(url);
context.Response.BinaryWrite(data);
}
catch (Exception ex)
{
context.Response.Clear();
context.Response.Write("Error occurred: " + ex.Message);
context.Response.ContentType = "text/plain";
context.Response.End();
}
}
public bool IsReusable { get { return false; } }
}

Categories

Resources