Xamarin.Forms - Open file with default app - c#

I need to open a file from storage. I used Launcher.OpenAsync(), but it always tries to open the file in PDF reader. Is there any other way to open a file with default app on Android?
This is the code I have already tried.
private void OpenDocument(string filePath)
{
var localFile = "file://" + filePath;
Launcher.OpenAsync(localFile);
}

string path = "your uri bla-bla-bla";
Launcher.OpenAsync
(new OpenFileRequest()
{
File = new ReadOnlyFile(path)
}
);

Related

Access denied error on Saving PDF data to documents directory in Xamarin iOS

I am having an app in which I am trying to share PDF file from my iOS device. So I am opening UIDocumentPickerViewController on my button click.
On selecting any PDF file from my device, I am trying to save it to documents directory and then send it to server.
I am successfully able to get the URL and when I try to save it to the documents folder, it gives me and error saying "Access Denied".
I have searched a lot but could not find a solution.
Below is my code.
private void UI_DidPickDocumentAtUrls(object sender, UIDocumentPickedAtUrlsEventArgs e)
{
storePDFData(e.Urls[0]);
}
private void storePDFData(NSUrl dataUrl)
{
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var directory = Path.Combine(documents, "Pdfs");
if (!File.Exists(directory))
{
Directory.CreateDirectory(directory);
}
Console.WriteLine(dataUrl.LastPathComponent);
var filename = Path.Combine(directory, dataUrl.LastPathComponent);
dataUrl.StartAccessingSecurityScopedResource();
FileStream fs = new FileStream(dataUrl.Path, FileMode.Open, FileAccess.ReadWrite);
StreamReader reader = new StreamReader(fs);
string content = reader.ReadToEnd();
//byte[] content = File.ReadAllBytes(dataUrl.Path);
if (content != null)
{
File.WriteAllText("file:///" + filename, content);
}
dataUrl.StopAccessingSecurityScopedResource();
}
Any help would be highly appreciated.
Thanks in advance.
The file path file:/// in iOS is invalid, you could try to use filename directly in this scenario.
File.WriteAllText(filename , content);

couldn't create files in my documents if my documents folder is redirect to another location in setup project

I'm creating a setup project, in the installation, I should create a file in My Documents folder, my code in Commit method looks like this:
base.Commit(savedState);
string folderPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp";
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\MyApp\Backup.xml";
if (!Directory.Exists(folderPath))
{
Directory.CreateDirectory(folderPath);
}
if (!File.Exists(path))
{
File.Create(path).Close();
}
using (TextWriter file = new StreamWriter(path, true))
{
file.WriteLine("adfasdfafdasdfaf");
}
This works well. But if I redirect My Documents to another location, such as D:\TestFolder, the code couldn't create the file in my new location, and the installation complete successfully. Anyone can help?
Edit:
I found Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) return me a wrong value. In Console Application, this return me a correct value, but in setup project, it return me an empty string.

Open a file in Windows 8 Metro App C#

I have an array with file paths (like "C:\...") and I would like to open them with the default app, from my app. Let's say it's a list and when I click one of them, it opens.
This is the way to launch a file async:
await Windows.System.Launcher.LaunchFileAsync(fileToLaunch);
It requires a Windows.Storage.StorageFile type of file, which has a Path read-only property, so I cannot set the Path. How can I open them once they're tapped/clicked?
Copied from my link in the comments:
// Path to the file in the app package to launch
string exeFile = #"C:\Program Files (x86)\Steam\steamapps\common\Skyrim\TESV.exe";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(exeFile);
if (file != null)
{
// Set the option to show the picker
var options = new Windows.System.LauncherOptions();
options.DisplayApplicationPicker = true;
// Launch the retrieved file
bool success = await Windows.System.Launcher.LaunchFileAsync(file, options);
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
You can of course omit the var options = **-Part so the ApplicationPicker doesn't get opened
or you can use this:
StorageFile fileToLaunch = StorageFile.GetFileFromPathAsync(myFilePath);
await Windows.System.Launcher.LaunchFileAsync(fileToLaunch);
you should use this method
http://msdn.microsoft.com/en-US/library/windows/apps/windows.storage.storagefile.getfilefrompathasync
on the Type StorageFile
This method is used to get file if you have a path already
the answer is within this sample: http://code.msdn.microsoft.com/windowsapps/Association-Launching-535d2cec
short answer is :
// First, get the image file from the package's image directory.
string fileToLaunch = #"images\Icon.Targetsize-256.png";
var file = await Windows.ApplicationModel.Package.Current.InstalledLocation.GetFileAsync(fileToLaunch);
// Next, launch the file.
bool success = await Windows.System.Launcher.LaunchFileAsync(file);
Best solution is this:
string filePath = #"file:///C:\Somewhere\something.pdf";
if (filePath != null)
{
bool success = await Windows.System.Launcher.LaunchUriAsync(new Uri(filePath));
if (success)
{
// File launched
}
else
{
// File launch failed
}
}
Tha app launches it with the system default application, in this case with the Adobe Reader.

How to download a file in IIS?

I have written two methods such as FileUpLoad() and FileDownLoad() to Upload and Download a single file in my local system.
void FileUpLoad()
{
string hfBrowsePath = fuplGridDocs.PostedFile.FileName; //fuplGridDocs is a fileupload control
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = Path.Combine(#"E:\Documents\");
FileInfo FP = new FileInfo(hfBrowsePath);
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value; //hfFileNameAutoGen is a hidden field
fuplGridDocs.PostedFile.SaveAs(destfile);
}
}
void FileDownLoad(LinkButton lnkFileName)
{
string filename = lnkFileName.Text;
string FilePath = Path.Combine(#"E:\Documents", filename);
fuplGridDocs.SaveAs(FilePath);
FileInfo fileToDownLoad = new FileInfo(FilePath);
if (fileToDownLoad.Exists)
{
Process.Start(fileToDownLoad.FullName);
}
else
{
lblMessage.Text = "File Not Saved!";
return;
}
}
While running the application before hosting it in IIS, I can upload a file to the desired location and can also retrieve a file from the saved location. But after publishing it in the localhost, I can only Upload a file. I could not download the saved file. There is no exception too. The Uploaded file is saved in the desired location. I don't know why it is not retrieving the file? Why I cant download the file in IIS? I have searched a lot in the internet, but couldn't find the solution. How to solve this? I am using Windows XP and IIS 5.1 version.
How do you expect your Web Application to do a Process.Start when you deploy this site to a server, your just going to be opening pictures on the server, not on the client PC.
I think this will answer your question: http://www.codeproject.com/Articles/74654/File-Download-in-ASP-NET-and-Tracking-the-Status-o
Also the download file is missing a slash after E:\Documents
another option is to add your wildcard to IIS MIME types

Creating an Epub file with a Zip library

HI All,
I am trying to zip up an Epub file i have made using c#
Things I have tried
Dot Net Zip http://dotnetzip.codeplex.com/
- DotNetZip works but epubcheck fails the resulting file (**see edit below)
ZipStorer zipstorer.codeplex.com
- creates an epub file that passes validation but the file won't open in Adobe Digital Editions
7 zip
- I have not tried this using c# but when i zip the file using there interface it tells me that the mimetype file name has a length of 9 and it should be 8
In all cases the mimetype file is the first file added to the archive and is not compressed
The Epub validator that I'am using is epubcheck http://code.google.com/p/epubcheck/
if anyone has succesfully zipped an epub file with one of these libraries please let me know how or if anyone has zipped an epub file successfully with any other open source zipping api that would also work.
EDIT
DotNetZip works, see accepted answer below.
If you need to control the order of the entries in the ZIP file, you can use DotNetZip and the ZipOutputStream.
You said you tried DotNetZip and it (the epub validator) gave you an error complaining about the mime type thing. This is probably because you used the ZipFile type within DotNetZip. If you use ZipOutputStream, you can control the ordering of the zip entries, which is apparently important for epub (I don't know the format, just surmising).
EDIT
I just checked, and the epub page on Wikipedia describes how you need to format the .epub file. It says that the mimetype file must contain specific text, must be uncompressed and unencrypted, and must appear as the first file in the ZIP archive.
Using ZipOutputStream, you would do this by setting CompressionLevel = None on that particular ZipEntry - that value is not the default.
Here's some sample code:
private void Zipup()
{
string _outputFileName = "Fargle.epub";
using (FileStream fs = File.Open(_outputFileName, FileMode.Create, FileAccess.ReadWrite ))
{
using (var output= new ZipOutputStream(fs))
{
var e = output.PutNextEntry("mimetype");
e.CompressionLevel = CompressionLevel.None;
byte[] buffer= System.Text.Encoding.ASCII.GetBytes("application/epub+zip");
output.Write(buffer,0,buffer.Length);
output.PutNextEntry("META-INF/container.xml");
WriteExistingFile(output, "META-INF/container.xml");
output.PutNextEntry("OPS/"); // another directory
output.PutNextEntry("OPS/whatever.xhtml");
WriteExistingFile(output, "OPS/whatever.xhtml");
// ...
}
}
}
private void WriteExistingFile(Stream output, string filename)
{
using (FileStream fs = File.Open(fileName, FileMode.Read))
{
int n = -1;
byte[] buffer = new byte[2048];
while ((n = fs.Read(buffer,0,buffer.Length)) > 0)
{
output.Write(buffer,0,n);
}
}
}
See the documentation for ZipOutputStream here.
Why not make life easier?
private void IonicZip()
{
string sourcePath = "C:\\pulications\\";
string fileName = "filename.epub";
// Creating ZIP file and writing mimetype
using (ZipOutputStream zs = new ZipOutputStream(sourcePath + fileName))
{
var o = zs.PutNextEntry("mimetype");
o.CompressionLevel = CompressionLevel.None;
byte[] mimetype = System.Text.Encoding.ASCII.GetBytes("application/epub+zip");
zs.Write(mimetype, 0, mimetype.Length);
}
// Adding META-INF and OEPBS folders including files
using (ZipFile zip = new ZipFile(sourcePath + fileName))
{
zip.AddDirectory(sourcePath + "META-INF", "META-INF");
zip.AddDirectory(sourcePath + "OEBPS", "OEBPS");
zip.Save();
}
}
For anyone like me who's searching for other ways to do this, I would like to add that the ZipStorer class from Jaime Olivares is a great alternative. You can copy the code right into your project, and it's very easy to choose between 'deflate' and 'store'.
https://github.com/jaime-olivares/zipstorer
Here's my code for creating an EPUB:
Dictionary<string, string> FilesToZip = new Dictionary<string, string>()
{
{ ConfigPath + #"mimetype", #"mimetype"},
{ ConfigPath + #"container.xml", #"META-INF/container.xml" },
{ OutputFolder + Name.Output_OPF_Name, #"OEBPS/" + Name.Output_OPF_Name},
{ OutputFolder + Name.Output_XHTML_Name, #"OEBPS/" + Name.Output_XHTML_Name},
{ ConfigPath + #"style.css", #"OEBPS/style.css"},
{ OutputFolder + Name.Output_NCX_Name, #"OEBPS/" + Name.Output_NCX_Name}
};
using (ZipStorer EPUB = ZipStorer.Create(OutputFolder + "book.epub", ""))
{
bool First = true;
foreach (KeyValuePair<string, string> File in FilesToZip)
{
if (First) { EPUB.AddFile(ZipStorer.Compression.Store, File.Key, File.Value, ""); First = false; }
else EPUB.AddFile(ZipStorer.Compression.Deflate, File.Key, File.Value, "");
}
}
This code creates a perfectly valid EPUB file. However, if you don't need to worry about validation, it seems most eReaders will accept an EPUB with a 'deflate' mimetype. So my previous code using .NET's ZipArchive produced EPUBs that worked in Adobe Digital Editions and a PocketBook.

Categories

Resources