I would like to WRITE to my HTML file in the ASSETS folder.
Please note because my HTML is related to other FILES/FOLDERS i cannot use the personal folder. I must write at the
Assets/HTML/mycharts.html
[MY WRITING code below return these errors
System.IO.File.WriteAllText("file:///android_asset/myGraphs/BarGraph.html", s);
]
ERRORS
UNHANDLED EXCEPTION: System.IO.DirectoryNotFoundException: Could not find a part of the path "//file:///android_asset/myGraphs/BarGraph.html".
at System.IO.FileStream..ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare,int,bool,System.IO.FileOptions) <0x00208>
at System.IO.FileStream..ctor (string,System.IO.FileMode,System.IO.FileAccess,System.IO.FileShare) <0x00057>
at System.IO.StreamWriter..ctor (string,bool,System.Text.Encoding,int) <0x00087>
at System.IO.StreamWriter..ctor (string,bool,System.Text.Encoding) <0x00037>
at
]
It is not possible to write to the assets folder or edit any files in there. It is read-only.
EDIT:
As suggested in the comments is to initially have your HTML in your assets and when needed they will be saved either on the SD card or in the private storage.
For storing files on SD card you can get the path to the SD card like so:
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "MyAppFolder";
"MyAppFolder" can be anything you want it to be, as long as it does not clash with some of the other folder names on the SD card, so make sure to check if it exists already. Combine that with a file name like so:
var extFileName = folder + Java.IO.File.Separator + "MyFile.txt";
Now write something to the file:
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
using (var fs = new FileStream(extFileName, FileMode.OpenOrCreate))
{
var buf = Encoding.ASCII.GetBytes("Hello, world!");
fs.Write(buf, 0, buf.Length);
}
If you want to store data in the internal storage you can get the path to the private storage with:
var folder = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
I achieved this based off the above solution with this code:
using (StreamReader sr = new StreamReader( this.contextCalledFrom.Assets.Open("pdfreport.html")))
html = sr.ReadToEnd();
MemoryStream memoryStream = new MemoryStream();
client.convertHtml(html, memoryStream);
var folder = Android.OS.Environment.ExternalStorageDirectory + Java.IO.File.Separator + "wpfolder";
if (!Directory.Exists(folder))
Directory.CreateDirectory(folder);
var extFileName = folder + Java.IO.File.Separator + "report.pdf";
using (FileStream file = new FileStream(extFileName, FileMode.Create, FileAccess.Write))
{
memoryStream.WriteTo(file);
}
Related
So i have this console app that looks through a folder for files, this folder only has .tiff images and the whole point of the app is convert them all into pdf files and finally merge them, and so I have this foreach cycle
foreach (var path in Directory.GetFiles(#"C:/Users/tferreira/Desktop/TIF_MarcadAgua"))
{
Console.WriteLine(path); // full path
Console.WriteLine(System.IO.Path.GetFileName(path)); // file name
Escrever("A fazer pdf");
imagens.Add(path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
FazerPdf(path);
if (File.Exists(path.ToUpper().Replace("A.TIF", "B.TIF")))
{
imagens.Add(path.ToUpper().Replace("A.TIF", "B.PDF"));
FazerPdf(path.ToUpper().Replace("A.TIF", "B.TIF"));
}
Escrever("O pdf foi gerado com sucesso. Caminho : " + path.ToUpper().Replace("A.TIF", "A.PDF").Replace("A.tif", "A.PDF"));
Escrever("Vai fazer o merge de todos os pdfs gerados.");
PdfMerge pm = new PdfMerge();
foreach (string imagem in imagens)
{
pm.AddDocument(imagem);
npages++;
}
}
And what is does is run trough the folder getting all the files and storing the path in that var path variable.
But when it´s actually time to make the pdf it gives that error i mentioned up top.
The line the error happens is this the fazerPDF funtion, thats where the pdf is made, since its a filepath error i will only show the error line since it keeps things easy to see.
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{
// some code
}
Things i know, the images do exist, the folder does exist.
Thanks for the help, if i myself find out what it is ill post a answer.
EDIT:
fazerPDF function
static public void FazerPdf(string Path)
{
string newPath = System.IO.Path.ChangeExtension(Path, ".pdf");
if (!File.Exists(Path.Replace("TIF", "PDF")))
using (FileStream stream = new FileStream(newPath.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
{
The problem seems to be this line:
using (FileStream stream = new FileStream(Path.Replace("TIF", "PDF"), FileMode.Create, FileAccess.Write))
This will replace all instances of "TIF" in Path with "PDF", no matter where they appear. For example:
c:\TIFs\IlikeTIFfiles\MyTIF.TIF
Would become:
c:\PDFs\IlikePDFfiles\MyPDF.PDF
If you simply want to replace the file extension part of the path, you can use Path.ChangeExtension to cut off the old extension and add the new one:
string newPath = System.IO.Path.ChangeExtension(path, ".pdf");
using (FileStream stream = new FileStream(newPath, FileMode.Create, FileAccess.Write))
Taking the example above, #"c:\TIFs\IlikeTIFfiles\MyTIF.TIF" would become #"c:\TIFs\IlikeTIFfiles\MyTIF.pdf"
See it in action.
I have a file which I upload to a temp folder after having done some image resizing as follows:
/uploads/temp/myfile.jpg
How can I read this file into a binary reader as follows if all I have is the file path as indicated above i.e. In the example below I get error:
Error in saving fileSystem.IO.DirectoryNotFoundException: Could not find a part of the path 'C:\\uploads\\temp\\myfile.jpg'
var fs = new FileStream('/uploads/temp/myfile.jpg', FileMode.Open);
using (var reader = new BinaryReader(fs))
{
image.ImageContent = reader.ReadBytes((int)fs.Length);
}
Managed to fix by doing the following:
var fs = new FileStream(HostingEnvironment.MapPath("~/") + "/uploads/temp/myfile.jpg", FileMode.Open);
I need to save the file when method OnDestroy is called and load same file when method OnCreate is called. At this time I can read json file easily from Assets (this works fine)
StreamReader reader = new StreamReader(Assets.Open("reiksmes.json"));
string JSONstring = reader.ReadToEnd();
Daiktai myList = JsonConvert.DeserializeObject<Daiktai>(JSONstring);
items.Add(myList);
, but I have some problems when I try to save(write) Daiktai class data to the same file I opened above. I tried:
string data = JsonConvert.SerializeObject(items);
File.WriteAllText("Assets\\reiksmes.json", data);
with this try I get error System.UnauthorizedAccessException: Access to the path "/Assets
eiksmes.json" is denied.
also tried:
string data = JsonConvert.SerializeObject(items);
StreamWriter writer = new StreamWriter(Assets.Open("reiksmes.json"));
writer.WriteLine(data);
and with this try I get error System.ArgumentException: Stream was not writable.
Summary:
I think I chose bad directory(Assets), I need to save and load data (json format). So where do I need to save them and how(give example)?
You can't save anything to assets. You can just read from it. You have to save the file to a different folder.
var fileName = "reiksmes.json";
string documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal); // Documents folder
var path = Path.Combine(documentsPath, fileName);
Console.WriteLine(path);
if (!File.Exists(path))
{
var s = AssetManager.Open(fileName);
// create a write stream
FileStream writeStream = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write);
// write to the stream
ReadWriteStream(s, writeStream);
}
I am trying to .tar.gz a list of files from a folder using SharpZipLib. The problem is no matter how pass the files paths - the result always contains the files paths - and not only the files thems selves. What am i missing here?
string filesFolder = "c:\\testfolder\\test\\";
List<string> filesToZip = new List<string>() { filesFolder +"test1", filesFolder +"test2"};
using (FileStream fs = new FileStream(filesFolder +"myGz.tar.gz" , FileMode.Create, FileAccess.Write, FileShare.None))
using (Stream gzipStream = new GZipOutputStream(fs))
using (TarArchive tarArchive = TarArchive.CreateOutputTarArchive(gzipStream))
{
foreach (string filename in filesToZip )
{
{
TarEntry tarEntry = TarEntry.CreateEntryFromFile(filename);
tarArchive.WriteEntry(tarEntry, false);
}
}
}
what i get is a "myGz.tar.gz" files. When i try to open it with 7.zip - i get the full folders structure in the archive - c:\testfolder\test\, and in it - "test1", "test".
How do i remove the files paths?
Thanks
I had the same problem, and I figured it out just after finding this question.
The key is to set the Name property of the tarEntry, before adding it into the archive.
TarEntry tarEntry = TarEntry.CreateEntryFromFile(filename);
tarEntry.Name = Path.GetFileName(filename);
tarArchive.WriteEntry(tarEntry, false);
I have problems in using SharpZipLib with isolated storage in WP7 to zip subfolders in isolated storage. My folder structure is like I'm having a rootFolder in isolated storage and inside that there is subFolder having some text files and more subfolders (contains .jpg and .png). I could go for Dotnetzip but I'm not sure it is available for WP7 or not and about its usage.
I am able to get all the file pathes in a list by recursively traversing on root folder. At present I am able to zip multiple files but only when they are inside a single folder.
Can't find way to zip subFolder with correct hierarchy of folder and file structure and save it inside isolated storage. Also needs to unzip it with correct folder and file structure.
You can do this with SharpZipLib for Silverlight/Windows Phone 7.
The following code is based on this example and demonstrates how to zip a root folder including subfolders and files.
Short overview:
button1_Click prepares some dummy folders and files for proof of concept: a folder root containing a file and two subfolders each also containing a file, then it calls CreateZip to compress the whole directory tree starting with root
CreateZip prepares the zip file and starts recursive folder compression by calling CompressFolder
CompressFolder adds all files in a given dir to the zip file and recurses into subdirectories
The code:
using System.IO.IsolatedStorage;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System.Text;
// Recurses down the folder structure
//
private void CompressFolder(string path, ZipOutputStream zipStream, int folderOffset, IsolatedStorageFile isf)
{
string[] files = isf.GetFileNames(System.IO.Path.Combine(path, "*.*"));
foreach (string filename in files)
{
string filenameWithPath = System.IO.Path.Combine(path, filename);
string entryName = filenameWithPath.Substring(folderOffset); // Makes the name in zip based on the folder
entryName = ZipEntry.CleanName(entryName); // Removes drive from name and fixes slash direction
ZipEntry newEntry = new ZipEntry(entryName);
newEntry.DateTime = isf.GetLastWriteTime(filenameWithPath).DateTime; // Note the zip format stores 2 second granularity
// To permit the zip to be unpacked by built-in extractor in WinXP and Server2003, WinZip 8, Java, and other older code,
// you need to do one of the following: Specify UseZip64.Off, or set the Size.
// If the file may be bigger than 4GB, or you do not need WinXP built-in compatibility, you do not need either,
// but the zip will be in Zip64 format which not all utilities can understand.
// zipStream.UseZip64 = UseZip64.Off;
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(filenameWithPath, System.IO.FileMode.Open, isf))
{
newEntry.Size = stream.Length;
}
zipStream.PutNextEntry(newEntry);
// Zip the file in buffered chunks
// the "using" will close the stream even if an exception occurs
byte[] buffer = new byte[4096];
using (IsolatedStorageFileStream streamReader = isf.OpenFile(filenameWithPath, System.IO.FileMode.Open))
{
StreamUtils.Copy(streamReader, zipStream, buffer);
}
zipStream.CloseEntry();
}
string[] folders = isf.GetDirectoryNames(System.IO.Path.Combine(path, "*.*"));
foreach (string folder in folders)
{
CompressFolder(System.IO.Path.Combine(path, folder), zipStream, folderOffset, isf);
}
}
// Compresses the files in the nominated folder, and creates a zip file on disk named as outPathname.
//
public void CreateZip(string outPathname, string password, string folderName)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream fsOut = new IsolatedStorageFileStream(outPathname, System.IO.FileMode.Create, isf))
{
ZipOutputStream zipStream = new ZipOutputStream(fsOut);
zipStream.SetLevel(3); //0-9, 9 being the highest level of compression
zipStream.Password = password; // optional. Null is the same as not setting.
// This setting will strip the leading part of the folder path in the entries, to
// make the entries relative to the starting folder.
// To include the full path for each entry up to the drive root, assign folderOffset = 0.
// int folderOffset = folderName.Length + (folderName.EndsWith("\\") ? 0 : 1); // hu: currently not used for WP7 sample
int folderOffset = 0;
CompressFolder(folderName, zipStream, folderOffset, isf);
zipStream.Close();
}
}
}
private void button1_Click(object sender, RoutedEventArgs e)
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
isf.CreateDirectory(#"root");
isf.CreateDirectory(#"root\subfolder1");
isf.CreateDirectory(#"root\subfolder2");
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"root\file0.txt", System.IO.FileMode.Create, isf))
{
byte[] bytes = Encoding.Unicode.GetBytes("hello");
stream.Write(bytes, 0, bytes.Length);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"root\subfolder1\file1.txt", System.IO.FileMode.Create, isf))
{
byte[] bytes = Encoding.Unicode.GetBytes("zip");
stream.Write(bytes, 0, bytes.Length);
}
using (IsolatedStorageFileStream stream = new IsolatedStorageFileStream(#"root\subfolder2\file2.txt", System.IO.FileMode.Create, isf))
{
byte[] bytes = Encoding.Unicode.GetBytes("world");
stream.Write(bytes, 0, bytes.Length);
}
}
CreateZip("root.zip", null, "root");
}