WIndows Phone 7 reading file to String - c#

I'm trying to read a file entirely to a String variable.
I did this:
String text;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream("k.dat", FileMode.Open, store))
using (var reader = new StreamReader(readStream))
{
text= reader.ReadToEnd();
}
textBlock1.Text = text;`
It gave me a "Operation not permitted on IsolatedStorageFileStream" message from an IsolatedStorageException.
What am I doing wrong?
I tried by adding a .txt and .xml file in the file name, but it didn't work.
Where am I to put the file anyway? I tried
~\Visual Studio 2010\Projects\Parsing\Parsing\k.dat
I'm parsing it later using:
XmlReader reader = XmlReader.Create(new StringReader(xmldata));
flagLink = false;
while (reader.Read())
{
//and so on

Try with..
string text;
string filename="k.txt";
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isolatedStorage));
text = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(text))
{
MessageBox.Show(text);
}
}
EDIT:
In case of xml,
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open); //you can use your filename just like above code
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.textbox1.Text = reader.ReadToEnd();
}
}
}
catch
{ }

This is the entire method and this worked fully:
String sFile = "k.dat";
IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
//myFile.DeleteFile(sFile);
if (!myFile.FileExists(sFile))
{
IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
dataFile.Close();
}
var resource = Application.GetResourceStream(new Uri(#"k.dat", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string rawData = streamReader.ReadToEnd();
return rawData;

Related

Download byte array from stream writer

Hi I am trying to make working this piece of code, after the copy of the word file template into a memory stream, read it and replace some text, I would convert the stream writer to byte array which will be used to download the result. Thanks in advance
public byte[] GetWordFile()
{
try
{
string sourceFile = Path.Combine("C:/[...]/somefile.docx");
using (MemoryStream inStream = new MemoryStream())
{
using (Stream fs = File.Open(sourceFile, FileMode.Open, FileAccess.Read))
{
fs.CopyTo(inStream);
}
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(inStream, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
}
docText = docText.Replace("numpol", "HAHAHHAHA");
using (MemoryStream outStream = new MemoryStream())
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
sw.Flush();
sw.BaseStream.CopyTo(outStream);
outStream.Position = 0;
return outStream.ToArray();
}
}
}
}
catch (Exception ex)
{
///...
}
}

The process cannot access the file because it is being used by another process

public bool ReadFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read);
StreamReader sr = new StreamReader(fs);
string res = sr.ReadToEnd();
if (res == "1")
return true;
else
return false;
}
public void WriteToFile()
{
string fname = "text.txt";
FileStream fs = null;
fs = new FileStream(fname, FileMode.Open,FileAccess.Write);
StreamWriter sw = new StreamWriter(fs);
sw.Write("1");
}
So it should work like if ReadFile returns false than i do WriteFile.
But when it reaches writefile, it throws IO expection:
The process cannot access the file ... because it is being used by another process
You aren't closing the file when you read it.
Put your FileStream and StreamReader objects in using statements:
using (var fs = new FileStream(fname, FileMode.OpenOrCreate,FileAccess.Read)) {
using (var sr = new StreamReader(fs)) {
//read file here
}
}
Make sure you do the same when you write to the file.
You need to dispose the StreamReader object in the ReadFile method. The StreamReader inherits from IDisposable and therfor you need to dispose the object.
Check this link for more info:StreamReader Class

Decompressing a zipfile into memory stream - C#

I have written code to store the encoded string of zip file into temp path and now I want to store the encoded zipfile string to memorystream instead of temp path. Can someone please help me how to read the stream and pass it as a string to ZipFile class...I am using DOTNETZIP library to unpack password protested file.
Please see below my code.
string tempPath = Path.GetTempPath();
foreach (ActivityMimeAttachment a in attachments.Entities)
{
if (a.FileName.EndsWith(".zip", StringComparison.OrdinalIgnoreCase))
{
string strcontent = a.Body;
byte[] filecontent = Convert.FromBase64String(strcontent); // unpack the base-64 to a blob
File.WriteAllBytes(tempPath + a.FileName, filecontent); // Working code creates a zip file
string attachmentfile = tempPath + a.FileName;
using (ZipFile zip = new ZipFile(attachmentfile))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
entry.ExtractWithPassword(tempPath, "password");
FileStream inFile;
byte[] binaryData;
string file = tempPath + entry.FileName;
inFile = new FileStream(file, FileMode.Open, FileAccess.Read);
binaryData = new Byte[inFile.Length];
long bytesRead = inFile.Read(binaryData, 0,
(int)inFile.Length);
inFile.Close();
You'll want to convert your file content to a memory stream (Stream filestream = new MemoryStream(filecontent)) then use ZipFile.Read(fileStream). Then use a StreamReader to get the contents out as a string. So try something like this (note it's untested):
string myString;
byte[] filecontent = Convert.FromBase64String(strcontent);
using (var filestream = new MemoryStream(filecontent))
{
using (ZipFile zip = ZipFile.Read(filestream))
{
foreach (ZipEntry entry in zip.Entries)
{
if ((entry.FileName.EndsWith(".xml", StringComparison.OrdinalIgnoreCase)) ||
(entry.FileName.EndsWith(".pdf", StringComparison.OrdinalIgnoreCase)))
{
using (var ms = new MemoryStream())
{
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
var sr = new StreamReader(ms);
myString = sr.ReadToEnd();
}
...
If the results should be a base64 string, do this:
entry.ExtractWithPassword(ms, "password");
ms.Position = 0;
myString = Convert.ToBase64String(ms.ToArray());
You may or may not have to reset the stream position, but it's good practice to.
Now you can use the results as a string without having to write to a file first.

Windows Phone C# -loading from text files

I have my program save the contents of 4 different text boxes into 4 separate text files using IsolatedStorageFile. This works fine, until I have to load them later. When I'm loading, all 4 text files are loaded into the first text box, and the remaining 3 are left blank.
Here's the code I'm using to save the files:
private void Button_Click_2(object sender, RoutedEventArgs e)
{
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
//Deletes any previous saved files
IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication();
storage.DeleteFile("ip-1.txt");
storage.DeleteFile("ip-2.txt");
storage.DeleteFile("ip-3.txt");
storage.DeleteFile("ip-4.txt");
// This saves users IP's into text files for later loading
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("ip-1.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box1.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-2.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box2.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-3.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box3.Text);
new StreamWriter(new IsolatedStorageFileStream("ip-4.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box4.Text);
Writer.Close();
}
and to load the files later:
private void Button_Click_4(object sender, RoutedEventArgs e)
{
// Loads IP's from text file or displays error message
//First clear the boxes...
box1.Text = "";
box2.Text = "";
box3.Text = "";
box4.Text = "";
//Load from text files...
IsolatedStorageFile fileStorage = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader Reader = null;
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-1.txt", FileMode.Open, fileStorage));
string textFile = Reader.ReadToEnd();
box1.Text = textFile;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-2.txt", FileMode.Open, fileStorage));
string textFile2 = Reader.ReadToEnd();
box2.Text = textFile2;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-3.txt", FileMode.Open, fileStorage));
string textFile3 = Reader.ReadToEnd();
box3.Text = textFile3;
}
catch
{
}
IsolatedStorageFile.GetUserStoreForApplication();
try
{
Reader = new StreamReader(new IsolatedStorageFileStream("ip-4.txt", FileMode.Open, fileStorage));
string textFile4 = Reader.ReadToEnd();
box4.Text = textFile4;
Reader.Close();
}
catch
{
}
// To sync with ListPicker
defaultPicker.ItemsSource = new List<string>() { { box1.Text }, { box2.Text }, { box3.Text }, { box4.Text } };
}
Any help into the right direction would be appreciated.
First, I suggest you stop eating all exceptions. At least in debug mode, have the empty catch blocks in a pragma.
I would drop the single declaration of Reader and create a new one per file:
try
{
using (StreamReader reader = new StreamReader(new IsolatedStorageFileStream("ip-1.txt", FileMode.Open, fileStorage)))
{
string textFile = reader.ReadToEnd();
box1.Text = textFile;
}
}
You aren't writing to the four files correctly. You need to reassign your Writer each time.
StreamWriter Writer = new StreamWriter(new IsolatedStorageFileStream("ip-1.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box1.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-2.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box2.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-3.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box3.Text);
Writer = new StreamWriter(new IsolatedStorageFileStream("ip-4.txt", FileMode.OpenOrCreate, fileStorage));
Writer.WriteLine(box4.Text);
Writer.Close();
In the future you should have something in your catch blocks to display any caught exceptions. In this case it would have told you that the three other files weren't able to be loaded because they didn't exist.

Isolated storage - opeation not permitted / while copying html file in Windows Phone

When I run
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
myStore.CopyTextFile("HTDocs\\help.html", true);
I have error: "Operation not permitted on IsolatedStorageFileStream." It's from tutorial. How should I fix that?
public static class ISExtensions
{
public static void CopyTextFile(this IsolatedStorageFile isf, string filename, bool replace = false)
{
if (!isf.FileExists(filename) || replace == true)
{
StreamReader stream = new StreamReader(TitleContainer.OpenStream(filename));
IsolatedStorageFileStream outFile = isf.CreateFile(filename);
//
//
string fileAsString = stream.ReadToEnd();
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(fileAsString);
outFile.Write(fileBytes, 0, fileBytes.Length);
stream.Close();
outFile.Close();
}
}
}
Try something like this:
// isolated storage
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
// access to resource files
StreamResourceInfo streamInfo = Application.GetResourceStream(new Uri(#"HTDocs\help.html", UriKind.Relative));
using (Stream origFileStream = streamInfo.Stream)
{
// open the filestream for the isostorage file and copy the content from the original stream
using (IsolatedStorageFileStream fileStream = myStore.CreateFile("help.html"))
{
origFileStream.CopyTo(fileStream);
origFileStream.Close();
}
}

Categories

Resources