path from isolated storage windows phone - windows-phone-7

hi i have a simple question how i can find the path of a file which had been already saved in the isolated storage
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(App.filePath, FileMode.Create, store))
{
byte[] buffer = new byte[1024];
while (e.Result.Read(buffer, 0, buffer.Length) > 0)
{
stream.Write(buffer, 0, buffer.Length);
}
stream.Close();
}
now i would read this file
i need this path to use it as a parameter of method
Epub epub =new Epub([file path])
any help will be greatly appreciated

If a file is in IsolatedStorage you either put there yourself or it's the one created by the system to store settings.
If you put it there you must have had the path at some point previously. You just need to track the file names (and paths) you're using.
You should not try and access the settings file directly.

Try this
using (var AppStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
string[] filenames=AppStorage.getFileNames();
//choose the filename you want or
//enumerate directories and read file names in each directory
string[] directories=AppStorage.getDirectories();
}
For each directory you have to add the filepath upto that directory just like in any windows file browsing.
Hope it helps.Post your further queries.

There is no need for you to get the path to the file if you are the one who put the file in the isolated storage. The entire guide to how properly read and write files to the app isostore is available here, and this should be your starting point.
The entire reading routine is limited to this:
using (IsolatedStorageFileStream fileStream = myIsolatedStorage.OpenFile("myFile.txt", FileMode.Open, FileAccess.Read))
{
using (StreamReader reader = new StreamReader(fileStream))
{
Console.WriteLine("Reading contents:");
Console.WriteLine(reader.ReadToEnd());
}
}
Where myIsolatedStorage is equal to IsolatedStorageFile.GetUserStoreForApplication() (akak your local app storage box).
No need for Reflection, as you showed in the comments. The can be relative to a folder, when you're attempting to read, so something like /MyFolder/myFile.txt will work as well, given that the folder exists.
Your problem is this - pushing the relative path in the isostore to the Epub class, which probably does not read directly from the isostore and uses a full path instead. The nature of the Windows Phone OS is such that it won't let a third-party application without proper permissions to access content directly through a full path reference. So you need to figure out a way to pass binary content to the class instead of a path.

Related

Access the Android Special Folder Path by using Environment

I want to save my logs to a folder which I can access with windows explorer. For example I want to create my log in the following path
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So I tried to use Environment variables... I get such as
/data/user/...
But here i cannot see the file what I created (using code I can access the path but I want to see in the explorer).
how I can create a path like above with code?
When I tried this code
var finalPath2 = Android.OS.Environment.GetExternalStoragePublicDirectory
(Android.OS.Environment.DataDirectory.AbsolutePath);
I get the path "/storage/emulated/0/data"
and
If i use the code
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.ApplicationData),"logs");
I get the following path like:
/data/user/0/MyApp/files/.config/logs
and
var logDirectory =Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments),"logs");
"/data/user/0/IM.OneApp.Presentation.Android/files/logs"
but unfortunately I cannot access this folder by explorer....
This PC\Galaxy A5 (2017)\Phone\Android\data\MyApp\files
So how to find out this path in c# by using environments?
Update:
when I give the following path hardcoded, it creates the file where I want..
logDirectory = "/storage/emulated/0/Android/data/MyApp/files/logs";
is there any environment to create this path? I can combine 2 environments and do some string processing in order to create this path. But maybe there is an easier way?
You are looking for the root of GetExternalFilesDir, just pass a null:
Example:
var externalAppPathNoSec = GetExternalFilesDir(string.Empty).Path;
Note: This is a Context-based instance method, you can access it via the Android application context, an Activity, etc... (see the link below to the Android Context docs)
Shared storage may not always be available, since removable media can be ejected by the user. Media state can be checked using Environment.getExternalStorageState(File).
There is no security enforced with these files. For example, any application holding Manifest.permission.WRITE_EXTERNAL_STORAGE can write to these files.
re: https://developer.android.com/reference/android/content/Context#getExternalFilesDir(java.lang.String)
string docFolder = Path.Combine(System.Environment.GetFolderPath
(System.Environment.SpecialFolder.MyDocuments), "logs");
string libFolder = Path.Combine(docFolder, "/storage/emulated/0/Android/data/MyApp/files/logs");
if (!Directory.Exists(libFolder))
{
Directory.CreateDirectory(libFolder);
}
string destinationDatabasePath = Path.Combine(libFolder, "temp.db3");
db.Backup( destinationDatabasePath, "main");

File replace in HttpPostedFileBase MVC3

If the file is uploading with the name already in the specified path, it is showing error. I want to replace with the new file. I have placed the error and the code. Please help to replace the existing image.
Error: The process cannot access the file '' because it is being used by another process.
Code:
[HttpPost]
public ActionResult MyUpload(HttpPostedFileBase file)
{
string filePath = string.Empty;
string path = "C:\\";
string filePath = string.Empty;
try
{
if (file != null && file.ContentLength > 0)
{
filePath = path + file.FileName;
file.SaveAs(filePath);
file.InputStream.Dispose();
GC.Collect();
// other operations, where can occur an exception
// (because the uploaded file can have a bad content etc.)
}
}
catch (Exception e)
{
}
}
Based upon what you posted, I would suggest the following:
[HttpPost]
public ActionResult Foo(HttpPostedFileBase file)
{
var path = #"C:\";
var filename = file.FileName;
file.SaveAs(System.IO.Path.Combine(path, filename));
// do stuff here.
return RedirectToAction("Index");
}
I had this very same issue. I had a sub-folder called "files" where I uploaded files using file.SaveAs() ('file' being of type 'HttpPostedFileBase' [using MVC]). After some local investigation and online research, it turns out that an IIS worker thread/process was locking my file. At first I thought {HttpPostedFileBase}.SaveAs() was somehow locking my file. I even tried to (first) close, and then dispose the {HttpPostedFileBase}.InputStream, and that also didn't help. In the end, it wasn't even related to the file upload process at all. After uploading the file (a PDF), I processed it using ITextSharp, but forgot to dispose of the object wrapper (so it was probably sitting in the GC). Because of that, the next file upload failed due to the locked existing file. BTW, I also tried file.InputStream.Dispose(); file.InputStream.Close(); GC.Collect();, but removed them all in the end, and it still works perfectly now. Bottom line, if an IIS Worker process is locking your file, there's probably a good reason - something somewhere in your code you are missing, and it most likely isn't the MVC framework or IIS itself gone rogue. ;) Also, as it turns out, {HttpPostedFileBase}.SaveAs() WILL overwrite files if they exist, so there's no need to delete them first.
One other tip: I read somewhere to watch out who is creating the files based on how your authorization is setup (whether or not you using an IIS process identity, or the logged-in user identity). In some cases, a file may be created by one logged in user, who then becomes the owner, and another file of the same name from a different user may become blocked; might be something to keep in mind in special cases (like intranet based web apps).

How to download a jpg from web to project folder in MVC3?

Hello everyone I would like to ask How can I download .jpg file from web to my project's folder which I have created "uploads" ?
I'm trying to downlaod youtube thumbnail image to my" uploads" folder.
My controller:
var fileName = Path.GetFileName(http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg);
var path = Path.Combine(Server.MapPath("~/uploads/"), fileName);
file.SaveAs(path);
Take a look at System.Net.WebClient, a .NET class which allows you to make requests for resources via HTTP.
http://msdn.microsoft.com/en-us/library/system.net.webclient(v=vs.100).aspx
Checked example provided.
var client = new System.Net.WebClient();
var uri = "http://img.youtube.com/vi/RUgd_GDPhYk/1.jpg";
// Here, we're just using the same filename as the resource we're after.
// You may wish to change this to include extra stuff because you'll
// inevitably run into a naming clash - especially with stuff like 1.jpg
var targetFilename = Path.GetFileName(uri);
client.DownloadFile(uri,
Path.Combine(Server.MapPath("~/uploads"), targetFilename));

Issue with WatchService in java 7

I'm using jdk7's WatchService API for monitoring the folder on file system.I'm sending a new file through
email to that folder, when the file comes into that folder i m triggering the ENTRY_CRATE option. its working fine.
But the issue is its generating two events of ENTRY_CREATE instead of one event which i'm invoking.
BELOW IS THE CODE:
Path dir = Paths.get(/var/mail);
WatchService watcher = dir.getFileSystem().newWatchService();
dir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
System.out.println("waiting for new file");
WatchKey watckKey = watcher.take();
List<WatchEvent<?>> events = watckKey.pollEvents();
System.out.println(events.size());
for(WatchEvent<?> event : events){
if(event.kind() == StandardWatchEventKinds.ENTRY_CREATE){
String fileCreated=event.context().toString().trim();
}
}
In the above code I'm gettng the events size as 2.
Can any one please help me in finding out the reason why i'm getting two events.
I am guessing that there might be some temporary files being created in the folder at the same time. Just check what are the name/paths of the file being created.

How to upload image in Windows Azure platform: best approach

Ihave a register form with an Image Upload and it doesn't work when I upload my package application in my Windows Azure server.
The image address in the server looks like this:
F:\sitesroot\0\Uploads\Users\9259826_2121813246965_1294840438_2490950_6619588_n.jpg
If I had this image url like this, with it's relative path:
http://dealma.cloudapp.net/Uploads/Users/9259826_2121813246965_1294840438_2490950_6619588_n.jpg
I would already solve the problem.
The current code I'm using to upload is this:
if (userImg != null && userImg.ContentLength > 0)
{
try
{
var fileName = Url.Encode(userImg.FileName);
//no overwrite files
var pathToCheck = Server.MapPath("~/Uploads/Users/" + fileName);
var savePath = Server.MapPath("~/Uploads/Users/");
var tempfileName = fileName;
int counter = 2;
while (System.IO.File.Exists(pathToCheck))
{
tempfileName = counter.ToString() + fileName;
pathToCheck = savePath + tempfileName;
counter++;
}
fileName = tempfileName;
var finalImg = Path.Combine(savePath, fileName);
userImg.SaveAs(finalImg);
//Img name
userSet.Picture = finalImg;
userSet.Thumbnail = finalImg;
}
catch (Exception ex)
{
Response.Write("Não foi possível fazer upload do arquivo: " + ex.Message);
}
}
Does anyone knows how to solve this problem?
As corvus stated, you are writing to "local storage" which is volatile and not shared across multiple instances of your virtual machine.
Blob storage lets you store arbitrary files, images, etc. Each item gets stored in its own blob. You also have the notion of a "container" - think of it as a top-level directory folder. There are no nested containers, but you can emulate them with path characters in the name (skip this for now, as you need a quick solution).
If you download the Windows Azure Platform Training Kit and look at the lab "Introduction to Cloud Services", it shows a Guestbook application, where photos are uploaded to blob storage. You will see how to set up a storage account, as well as writing the code to push your file to a blob instead of the local file system. Here's a snippet from the sample:
Initialize blob client, and set up container to store your files:
var storageAccount =
CloudStorageAccount.FromConfigurationSetting("DataConnectionString");
// create blob container for images
blobStorage = storageAccount.CreateCloudBlobClient();
CloudBlobContainer container = blobStorage.GetContainerReference("uploads");
container.CreateIfNotExist();
Now, in your upload handler, you'd write to a blob instead of local file system:
string uniqueBlobName = string.Format("uploads/image_{0}{1}",
Guid.NewGuid(), Path.GetExtension(UserImg.FileName));
CloudBlockBlob blob = blobStorage.GetBlockBlobReference(uniqueBlobName);
blob.Properties.ContentType = UserImg.PostedFile.ContentType;
// note: there are several blob upload methods -
// choose the best one that fits your app
blob.UploadFromStream(UserImg.FileContent);
You'll see the full working sample once you download the Platform Training Kit.
You are trying to save the image to the virtual machine where web role handling your request resides.
Probably there is more than one web role instance in your application. So, the file gets saved on one machine, but next request is served by another web role and virtual machine that doesn't have this file.
So, good idea is to save all data that needs to be accessible from any web role, to blobs. If you have some static data, you can put this data into package with your web role. All other data should reside in blobs.
If you don't want to modify the code of your application, you can map a part of blob storage as another hard drive to every instance of your web role. In this case, you just need to write received data to this mapped disk. The results will be accessible from any web role.

Resources