Read a file from Windows Phone 7 - c#

I have a folder called data/ in my project that contains txt files.
I configured Build Action to resources to all files.
I tried these different ways:
method 1
var resource = Application.GetResourceStream(new Uri(fName, UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
Debug.WriteLine(streamReader.ReadToEnd());
method 2
IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileNames = myIsolatedStorage.GetFileNames("*.txt");
method 3
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader fileReader = new StreamReader(new IsolatedStorageFileStream(fName, FileMode.Open, isf)))
{
while (!fileReader.EndOfStream)
{
string line = fileReader.ReadLine();
al.Add(line);
Debug.WriteLine(line);
}
}
}
Now, i tried different ways to read files without success, why?
Where is the problem?
What's wrong with these methods?
fName is the name of the file.
It's necessary the full path data/filename.txt? It's indifferent...
please help me with this stupid issue,
thanks.

Your 2nd & 3rd approaches are wrong. When you include a text file locally in your app, you can't refer it via the IS. Instead, use this function, it will return the file content if found else it will return "null". It works for me, hope it works for you.
Note, if the file is set as content, the filePath = "data/filename.txt" but if it is set as resource it should be referred like this filePath = "/ProjectName;component/data/filename.txt". That may be why your 1st approach might have failed.
private string ReadFile(string filePath)
{
//this verse is loaded for the first time so fill it from the text file
var ResrouceStream = Application.GetResourceStream(new Uri(filePath, UriKind.Relative));
if (ResrouceStream != null)
{
Stream myFileStream = ResrouceStream.Stream;
if (myFileStream.CanRead)
{
StreamReader myStreamReader = new StreamReader(myFileStream);
//read the content here
return myStreamReader.ReadToEnd();
}
}
return "NULL";
}

Related

XML file from ZIP Archive is incomplete in C#

I've work with large XML Files (~1000000 lines, 34mb) that are stored in a ZIP archive. The XML file is used at runtime to store and load app settings and measurements. The gets loadeted with this function:
public static void LoadFile(string path, string name)
{
using (var file = File.OpenRead(path))
{
using (var zip = new ZipArchive(file, ZipArchiveMode.Read))
{
var foundConfigurationFile = zip.Entries.First(x => x.FullName == ConfigurationFileName);
using (var stream = new StreamReader(foundConfigurationFile.Open()))
{
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
var newObject = xmlSerializer.Deserialize(stream);
CurrentConfiguration = null;
CurrentConfiguration = newObject as ProjectConfiguration;
AddRecentFiles(name, path);
}
}
}
}
This works for most of the time.
However, some files don't get read to the end and i get an error that the file contains non valid XML. I used
foundConfigurationFile.ExtractToFile();
and fount that the readed file stops at line ~800000. But this only happens inside this code. When i open the file via editor everything is there.
It looks like the zip doesnt get loaded correctly, or for that matter, completly.
Am i running in some limitations? Or is there an error in my code i don't find?
The file is saved via:
using (var file = File.OpenWrite(Path.Combine(dirInfo.ToString(), fileName.ToString()) + ".pwe"))
{
var zip = new ZipArchive(file, ZipArchiveMode.Create);
var configurationEntry = zip.CreateEntry(ConfigurationFileName, CompressionLevel.Optimal);
var stream = configurationEntry.Open();
var xmlSerializer = new XmlSerializer(typeof(ProjectConfiguration));
xmlSerializer.Serialize(stream, CurrentConfiguration);
stream.Close();
zip.Dispose();
}
Update:
The problem was the File.OpenWrite() method.
If you try to override a file with this method it will result in a mix between the old file and the new file, if the new file is shorter than the old file.
File.OpenWrite() doenst truncate the old file first as stated in the docs
In order to do it correctly it was neccesary to use the File.Create() method. Because this method truncates the old file first.

"File being used" error causes searching for specific text to fail

I am listing files in a given folder (log files) and allow downloading the file as well as searching for a given text in all files. Search is not working.
I tried to download the files and noticed for today's files I get "Error : The process cannot access the file 'Z:\abcd.log' because it is being used by another process.". I contacted developer who generates this log file and was told that the log file for today is kept open until midnight (he is not doing open/write/close).
In my download-file code, I was using:
fStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.Read);
I changed it to:
fStream = new FileStream(filepath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
This fixed the download issue; but search still does not work and I need some help.
I am using ReadAllLines that by my understanding (I could be wrong) opens and closes the file.
public string SearchFiles(string SearchStr, string FolderName, string DaysPrior)
{
string JSONresult = string.Empty;
var dir = Server.UrlDecode(FolderName);
System.IO.DirectoryInfo di = new System.IO.DirectoryInfo(dir);
int iDaysPrior = 0;
if (!string.IsNullOrEmpty(DaysPrior))
iDaysPrior = int.Parse(DaysPrior);
var fileList = di.GetFiles().Where(x => x.LastWriteTime.Date >= DateTime.Today.AddDays(0 - iDaysPrior)).OrderByDescending(f => f.LastWriteTime);
foreach (System.IO.FileInfo fi in fileList)
{
foreach (var line in File.ReadAllLines(fi.FullName))
{
// Using custom extension method
if (line.Contains(SearchStr, StringComparison.CurrentCultureIgnoreCase))
{
// Do something
}
}
}
return JSONresult;
}
Solution See comments for the credit, solution provided by psubsee2003.
The issue is that ReadAllLines, at the end, uses StreamReader in FileAccess.Read mode. It cannot share a file with another application with Read/Write access to the file. The solution, according to the post (and it worked for me) was to write your own ReadAllLines. Following code is from the post, in case the post itelf disappears one day.
public string[] WriteSafeReadAllLines(String path)
{
using (var csv = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
using (var sr = new StreamReader(csv))
{
List<string> file = new List<string>();
while (!sr.EndOfStream)
{
file.Add(sr.ReadLine());
}
return file.ToArray();
}
}

C# streamwriter denies access to save xml file into MyDocuments

I created a little game with the option to save the character into an XML File, now I wanted the Savegame-Folder location to be at MyDocuments, but every time I try to save the XML I just get an access denied from my streamwriter. Does someone know how to fix that?
Here's my code:
// Create the folder into MyDocuments (works perfectly!)
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"Arena\Savegames\"));
// This one should the save the file into the directory, but it doesn't work :/
path = Path.GetDirectoryName(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Arena\Savegames\" + hero.created + ".xml"));
The Streamwriter:
public class SaveLoadGame
{
public void SaveGameData(object IClass, string filename)
{
StreamWriter saveGameWriter = null;
try
{
XmlSerializer saveGameSerializer = new XmlSerializer((IClass.GetType()));
saveGameWriter = new StreamWriter(filename);
saveGameSerializer.Serialize(saveGameWriter, IClass);
}
finally
{
if (saveGameWriter != null)
saveGameWriter.Close();
saveGameWriter = null;
}
}
}
public class LoadGameData<T>
{
public static Type type;
public LoadGameData()
{
type = typeof(T);
}
public T LoadData(string filename)
{
T result;
XmlSerializer loadGameSerializer = new XmlSerializer(type);
FileStream dataFilestream = new FileStream(filename, FileMode.Open, FileAccess.Read, FileShare.Read);
try
{
result = (T)loadGameSerializer.Deserialize(dataFilestream);
dataFilestream.Close();
return result;
}
catch
{
dataFilestream.Close();
return default(T);
}
}
}
I tried some of the solutions I found here on stackoverflow like this and this. But didn't work for me, maybe someone else has an idea how I can get access to that folder? Or maybe just save it somewhere I actually have access, because ApplicationData and CommonApplicationData didn't work for me either.
Btw I'm using Virtual Box with Win10_Preview, I hope it's not because of this.
Edit: Before trying to save the files to MyDirectory I managed to save the files into my Debug folder of the project like this:
path = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) + #"\Savegames\" + hero.created + ".xml";
gameSaver.SaveGameData(myCharacterObject, path);
Thanks to Jon Skeet I figured out that I was just using the directory name, instead of the full path to save my file. So I just fixed the code to this:
// Creating the folder in MyDocuments
Directory.CreateDirectory(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments), #"Arena\Savegames\"));
// Setting the full path for my streamwriter
path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments) + #"\Arena\Savegames\" + hero.created + ".xml";

Sharing violation during save as on Ubuntu Linux

I'm new to C# and I'm having a bit of an issue when saving to a new file. My program has two options for saving: save & save as.
I was getting a sharing violation error when saving, but I fixed that by closing the previous filestream. However, I still cant figure out why my save as code is giving me a sharing violation error.
Here's the code:
// get a file stream from the file chooser
FileStream file = File.OpenWrite(saveFc.Filename);
// check to see if the file is Ok
bool fileOk = file.CanWrite;
if (fileOk == true)
{
// get the filename
string filename = file.Name;
// store the filename for later use
UtilityClass.filename = filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// get a StreamWriter
StreamWriter writer = File.CreateText(filename);
// write to the file
writer.Write(text);
// close/save the file
writer.Close();
file.Close();
}
}
// close the file c
If you could help me figure it out that would be much appreciated. Thanks!
You're opening the same file twice:
FileStream file = File.OpenWrite(saveFc.Filename);
And:
string filename = file.Name;
StreamWriter writer = File.CreateText(filename);
Your code could probably be simplified to:
using (var writer = File.CreateText(saveFc.Filename))
{
// store the filename for later use
UtilityClass.filename = saveFc.Filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// write the text
writer.Write(text);
}
If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

Operation not permitted on IsolatedStorageFileStream error

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)
{
...

Categories