I need to rename a file in the IsolatedStorage. How can I do that?
There doesn't appear to anyway in native C# to do it (there might be in native Win32, but I don't know).
What you could do is open the existing file and copy it to a new file and delete the old one. It would be slow compared to a move, but it might be only way.
var oldName = "file.old"; var newName = "file.new";
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream(oldName, FileMode.Open, store))
using (var writeStream = new IsolatedStorageFileStream(newName, FileMode.Create, store))
using (var reader = new StreamReader(readStream))
using (var writer = new StreamWriter(writeStream))
{
writer.Write(reader.ReadToEnd());
}
In addition to the copy to a new file, then delete the old file method, starting with Silverlight 4 and .NET Framework v4, IsolatedStorageFile exposes MoveFile and MoveDirectory methods.
Perfectly execute this piece of code
string oldName="oldName";
string newName="newName";
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(oldName);
await file.RenameAsync(newName);
Related
I'm using System.IO.Compression in order to compress a file into a .zip, below the source code:
using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew)){
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update)){
ZipArchiveEntry readmeEntry = archive.CreateEntry(#"C:\Users\soc\myFold\someFile.xml");
}
}
This piece of code works well, but unfortunately in the .zip there's the entire sequence of folders (C: -> Users -> ... -> someFile.xml); can I obtain a final .zip with ONLY the file I need? I know that with other libraries this fact is possible (DotNetZip add files without creating folders), but I would like to know if it were possible do the same with the standard library.
You seem to be under the impression that the file will be added to the archive, which is not the case. CreateEntry merely creates an entry with the specified path and entry name, you still need to write the actual file.
In fact, the code in your question is quite similar to the code in the documentation, so I assume you got it from there?
Anyway, to get only the file name you can use Path.GetFileName and then you can write the actual file content to the zip entry.
var filePath = #"C:\temp\foo.txt";
var zipName = #"C:\temp\foo.zip";
using (FileStream zipToOpen = new FileStream(zipName, FileMode.CreateNew))
{
using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Update))
{
ZipArchiveEntry readmeEntry = archive.CreateEntry(Path.GetFileName(filePath));
using (StreamReader reader = new StreamReader(filePath))
using (StreamWriter writer = new StreamWriter(readmeEntry.Open()))
{
writer.Write(reader.ReadToEnd());
}
}
}
The code above will create an archive with foo.txt in the root and with the content of the source file, without any additional directories.
How can I decompress (.zip) files without extracting to a new location in the .net framework? Specifically, I'm trying to read a filename.csv.zip into a DataTable.
I'm aware of .extractToDirectory (which is within ZipArchive) but I just want to extract it into an object in c# and I would like to not create a new file.
Hoping to be able to do this w/o third party libraries, but I'll take what I can get.
May be some bugs because I never tested this, but here you go:
List<byte[]> urmom = new List<byte[]>();
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
foreach (ZipArchiveEntry entry in archive.Entries)
using (StreamReader r = new StreamReader(entry.Open()))
urmom.Add(r.ReadToEnd(entry));
Basically you use the ZipArchive's openread class to iterate through each entry. At this point, you can use the streamreader to read each entry. From there you can create a file from the stream and even read the filename if you want to. My code doesn't do this, a bit of laziness on my part.
Keep in mind that a compressed stream might contain multiple files. To resolve this is required to iterate through all entries of zip file in order to retrieve them and treat separately.
The sample bellow converts a sequence of bytes in a list of string where each one is the context of the files included in zipped folder:
public static IEnumerable<string> DecompressToEntriesTextContext(byte[] input)
{
var zipEntriesContext = new List<string>();
using (var compressedStream = new MemoryStream(input))
using (var zip = new ZipArchive(compressedStream, ZipArchiveMode.Read))
{
foreach(var entry in zip.Entries)
{
using (var entryStream = entry.Open())
using (var memoryEntryStream = new MemoryStream())
using (var reader = new StreamReader(memoryEntryStream))
{
entryStream.CopyTo(memoryEntryStream);
memoryEntryStream.Position = 0;
zipEntriesContext.Add(reader.ReadToEnd());
}
}
}
return zipEntriesContext;
}
I am writing a Xamarin.Form PLC for Android and iOS, and have a place where I need to write some application stuff to a text file embedded resource. I've implemented reading from the same text file successfully, with same syntax just using StreamReader, but the StreamWriter implementation looks like this:
Assembly assembly = GetType().GetTypeInfo().Assembly;
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource)) {
using (StreamWriter writer = new StreamWriter(stream)) {
//do stuff
}
}
StreamWriter is throwing an argument of "Stream is not writeable" at System.IO.StreamWriter. Am I doing something obvsiously wrong? Why is the Stream Readable but not Writeable using the same assembly/resource/stream construction?
The stream from GetManifestResourceStream is not writable. The stream's file is embedded in the assembly at build time and cannot be changed. You'll have to write the file to disk before you can write to it.
string resource = "jetStream.Results.settings.txt";
using (Stream stream = assembly.GetManifestResourceStream(resource))
using (var fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Personal)), FileMode.Create, FileAccess.Write))
using (var stream = new MemoryStream())
using (var writer = new StreamWriter(fs))
{
rStream.Stream.CopyTo(stream);
writer.Write(stream.ToArray());
}
After this you can read and write to the file on disk.
Depending on what you want to write, if it's just things like application settings, you can use the Application.Properties collection http://www.kymphillpotts.com/exploring-xamarin-forms-1-3-properties-dictionary/ otherwise I agree with Jon's answer.
Is there any techniques or you can share some code snippets on how to save any kind of file that is supported by wp7?
You can write and read basically everything from/into the isolated storage. You can create folders and files etc. Think of it as a whole filesystem just for your app.
You can write text files like:
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var fileStream = new IsolatedStorageFileStream("filename", FileMode.Create, myIsolatedStorage))
using (StreamWriter writer = new StreamWriter(fileStream))
{
writer.Write("Hi I'm a string!");
}
or binary data like:
using (var myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
using (var fileStream = new IsolatedStorageFileStream("filename", FileMode.Create, myIsolatedStorage))
using (var writer = new BinaryWriter(fileStream))
{
// write some bytes
writer.Write(new byte[]{0, 1, 2, 3}, 0, 4);
}
See this tutorial for more examples.
The following links will help you understand clearly about IsolatedStorage in windows phone 7, with example code blocks and usage
IsolagedStorageFile Msdn documentation with example
Working with IsolatedStorage Files
It gives operation not permitted on IsolatedStorageFileStream error when I try to save the content of the file in the fileStream fs.
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileList = appStorage.GetFileNames();
foreach (string fileName in fileList)
{
using (var file = appStorage.OpenFile(fileName, FileMode.Open))
{
if (fileName != "__ApplicationSettings")
{
var fs = new IsolatedStorageFileStream(fileName, FileMode.Open, FileAccess.Read, appStorage);
string abc = fs.ToString();
meTextBlock.Text = abc;
//MemoryStream ms = appStorage.OpenFile(fileName, FileMode.Open, FileAccess.Read);
clientUpload.UploadAsync(SkyDriveFolderId, fileName, fs);
}
}
}
Why did you add the inner using (var file = appStorage.OpenFile(fileName, FileMode.Open))?
Seems to me the problem is that you're opening a stream to read the file and then opening another, without closing the previous one!
If you remove that line (seems not to be doing anything there) it should work fine.
Oh, and the fs.ToString() will only get you the Type name, not the file content; to read the file, use a StreamReader with the fs.
This error consistently occurs when an isolated storage file is opened by one stream (or reader or else) and, is being accessed by another object while the first stream (or reader, or else) have not yet relinquished the file. Go through your code carefully in all places where you access isolated storage files and make sure you close each file before something else is accessing it. Pedro Lamas is correct for this particular case, I just wanted to provide some general feedback. If you search google for "Operation not permitted on IsolatedStorageFileStream error" questions and answers, you will see the trend. The error message could be more descriptive though.
Try this approach
using (var isf = IsolatedStorageFile.GetUserStoreForApplication())
{
if (IsolatedStorageFile.IsEnabled)
{
if (isf.FileExists(localFileName))
{
using (var isfs = new IsolatedStorageFileStream(localFileName, FileMode.Open, isf))
{
using (var sr = new StreamReader(isfs))
{
var data = sr.ReadToEnd();
if (data != null)
{
...