So I've been working on a simple game and I wanted to implement a highscore system. Once the player loads up the main page for the first time a new text file is created ("hsc.txt") and some fake values are inserted which are later on split up by the program, however, currently my code throws a System.IO.IsolatedStorage.IsolatedStorageException and I can't seem to find the problem. I've looked up the error that I got from the message box which was "- operation not permitted" but all the solutions that were posted don't seem to work. I have tried closing the streams but it doesn't seem to work.
Any advice would be highly appreciated.
private void hasHighscores()
{
String fileName = "hsc.txt";
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(fileName))
{
isoStorage.CreateFile(fileName);
using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Append, FileAccess.Write, isoStorage))
{
using (var fileStream = new StreamWriter(isoStream))
{
fileStream.WriteLine("n1:666,n2:777,n3:888,h1:666,h2:777,h3:888");
fileStream.Close();
}
isoStream.Close();
}
}
}
}
So far I have: a) changed the FileMode b) changed the FileAccess and a few other "quickfixes" that I don't even remember.
The CreateFile method returns a stream to the created file, and keeps it open. Therefore, when you try to open a stream to that same file in the next line, it throws an exception because the file is already locked.
You can rewrite your code as follows:
private void hasHighscores()
{
String fileName = "hsc.txt";
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(fileName))
{
using (var isoStream = isoStorage.CreateFile(fileName))
{
using (var fileStream = new StreamWriter(isoStream))
{
fileStream.WriteLine("n1:666,n2:777,n3:888,h1:666,h2:777,h3:888");
}
}
}
}
}
I've also removed the stream.Close() instructions. The close method is automatically called when you enclose the stream in a using statement.
Related
I am trying to access the file that does not exist. what error will it throw.?
using (var fileStream = new FileStream(#"c:\file.txt", FileMode.Open))
{
// read from file or write to file
}
What will happen if file not exist.?
As mentioned Here opening file when file is non existant throws FileNotFoundException. Therefore to make it work do this :
var fileName = "c:\file.txt";
if(File.Exists(fileName)
{
using (var fileStream = new FileStream(#"c:\file.txt", FileMode.Open))
{
//code
}
or even :
try{
using (var fileStream = new FileStream(#"c:\file.txt", FileMode.Open))
{
//code
}
}
catch(FileNotFoundException e)
{
//code
}
Because of my hatred for people commenting like "google it!" "look it up in documentation" I decided to answer this question despite that it is typical documentation search. Stack should be about question-answer.
Addition to above answer It may throw UnauthorizedAccessException too.
I'm attempting to use StreamReader and StreamWriter to grab a temporary output log (.txt format) from another application.
The output log is always open and constantly written to.
Unhelpfully if the application closes or crashes, the log file ends up deleted - hence the need for a tool that can grab the information from this log and save it.
What my program currently does is:
Create a new .txt file, and stores the path of that file as the
string "destinationFile".
Finds the .txt log file to read, and stores the path of that file as
the string "sourceFile"
It then passes those two strings to the method below.
Essentially I'm trying to read the sourceFile one line at a time.
Each time one line is read, it is appended to destinationFile.
This keeps looping until the sourceFile no longer exists (i.e. the application has closed or crashed and deleted its log).
In addition, the sourceFile can get quite big (sometimes 100Mb+), and this program may be handling more than one log at a time.
Reading the whole log rather than line by line will most likely start consuming a fair bit of memory.
private void logCopier(string sourceFile, string destinationFile)
{
while (File.Exists(sourceFile))
{
string textLine;
using (var readerStream = File.Open(sourceFile,
FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
using (var reader = new StreamReader(readerStream))
{
while ((textLine = reader.ReadLine()) != null)
{
using (FileStream writerStream = new FileStream(destinationFile,
FileMode.Append,
FileAccess.Write))
using (StreamWriter writer = new StreamWriter(writerStream))
{
writer.WriteLine(textLine);
}
}
}
}
}
The problem is that my WPF application locks up and ceases to respond when it reaches this code.
To track down where, I put a MessageBox just before the writerStream line of the code to output what the reader was picking up.
It was certainly reading the log file just fine, but there appears to be a problem with writing it to the file.
As soon as it reaches the using (FileStream writerStream = new FileStream part of the code, it stops responding.
Is using the StreamWriter in this manner not valid, or have I just gone and dome something silly in the code?
Am also open to a better solution than what I'm trying to do here.
Simply what I understand is you need to copy a file from source to destination which may be deleted at any time.
I'll suggest you to use FileSystemWatcher to watch for source file changed event, then just simply copy the whole file from source to destination using File.Copy.
I've just solved the problem, and the issue was indeed something silly!
When creating the text file for the StreamWriter, I had forgotten to use .Dispose();. I had File.Create(filename); instead of File.Create(filename).Dispose(); This meant the text file was already open, and the StreamWriter was attempting to write to a file that was locked / in use.
The UI still locks up (as expected), as I've yet to implement this on a new thread as SteenT mentioned. However the program no longer crashes and the code correctly reads the log and outputs to a text file.
Also after a bit of refinement, my log reader/writer code now looks like this:
private void logCopier(string sourceFile, string destinationFile)
{
int num = 1;
string textLine = String.Empty;
long offset = 0L;
while (num == 1)
{
if (File.Exists(sourceFile))
{
FileStream stream = new FileStream(sourceFile, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
using (new StreamReader(stream))
{
stream.Seek(offset, SeekOrigin.Begin);
TextReader reader2 = new StreamReader(stream);
while ((textLine = reader2.ReadLine()) != null)
{
Thread.Sleep(1);
StreamWriter writer = new StreamWriter(destinationFile, true);
writer.WriteLine(textLine);
writer.Flush();
writer.Close();
offset = stream.Position;
}
continue;
}
}
else
{
num = 0;
}
}
}
Just putting this code up here in case anyone else is looking for something like this. :)
So I've been working on a simple game and I wanted to implement a highscore system. Once the player loads up the main page for the first time a new text file is created ("hsc.txt") and some fake values are inserted which are later on split up by the program, however, currently my code throws a System.IO.IsolatedStorage.IsolatedStorageException and I can't seem to find the problem. I've looked up the error that I got from the message box which was "- operation not permitted" but all the solutions that were posted don't seem to work. I have tried closing the streams but it doesn't seem to work.
Any advice would be highly appreciated.
private void hasHighscores()
{
String fileName = "hsc.txt";
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(fileName))
{
isoStorage.CreateFile(fileName);
using (var isoStream = new IsolatedStorageFileStream(fileName, FileMode.Append, FileAccess.Write, isoStorage))
{
using (var fileStream = new StreamWriter(isoStream))
{
fileStream.WriteLine("n1:666,n2:777,n3:888,h1:666,h2:777,h3:888");
fileStream.Close();
}
isoStream.Close();
}
}
}
}
So far I have: a) changed the FileMode b) changed the FileAccess and a few other "quickfixes" that I don't even remember.
The CreateFile method returns a stream to the created file, and keeps it open. Therefore, when you try to open a stream to that same file in the next line, it throws an exception because the file is already locked.
You can rewrite your code as follows:
private void hasHighscores()
{
String fileName = "hsc.txt";
using (var isoStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (!isoStorage.FileExists(fileName))
{
using (var isoStream = isoStorage.CreateFile(fileName))
{
using (var fileStream = new StreamWriter(isoStream))
{
fileStream.WriteLine("n1:666,n2:777,n3:888,h1:666,h2:777,h3:888");
}
}
}
}
}
I've also removed the stream.Close() instructions. The close method is automatically called when you enclose the stream in a using statement.
Here is the code im using to write and read from text file.
StreamWriter sw1 = new StreamWriter("DataNames.txt");
sw1.WriteLine(textBox1.Text);
sw1.Close();
StreamWriter sw2 = new StreamWriter("DataNumbers.txt");
sw2.WriteLine(textBox2.Text);
sw2.Close();
FileInfo file1 = new FileInfo("DataNames.txt");
StreamReader sr1 = file1.OpenText();
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
The thing is that when I click my button to save data from my textboxes to my text files an error appears that says "The process cannot access the file 'C:\xxxx\xxxxxx\xxxxx\xxxx\xxxxx\xxxxx.txt' because it is being used by another process."
Can anyone tell me why I have this error and maybe help me fix it
Try added a using statment around your streams to make sure they are Disposed otherwise the file is still locked to the stream
Example:
//Write
using (StreamWriter sw1 = new StreamWriter("DataNames.txt"))
{
sw1.WriteLine(textBox1.Text);
}
using (StreamWriter sw2 = new StreamWriter("DataNumbers.txt"))
{
sw2.WriteLine(textBox2.Text);
}
// Read
foreach (var line in File.ReadAllLines("DataNames.txt"))
{
listBox1.Items.Add(line);
}
foreach (var line in File.ReadAllLines("DataNumbers.txt"))
{
listBox2.Items.Add(line);
}
It appears you do not close the file after you read it. After you call FileInfo.OpenText you get a StreamReader which has to be closed, either via Close method, or even better, with a using statement.
But there are already methods that do all that for you, have a look at File.WriteAllText,
File.AppendAllText and File.ReadAllLines methods.
You need to Close the StreamReader object once you do not need it any more. This should fix this issue.
I.e.
StreamReader sr1 = file1.OpenText();
try {
while (!sr1.EndOfStream)
{
listBox1.Items.Add(sr1.ReadLine());
}
}
finally {
sr1.Close();
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
StreamReader sr2 = file2.OpenText();
try {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
finally {
sr2.Close();
}
You have opened files but not closed.
StreamReader sr1 = file1.OpenText();
StreamReader sr2 = file2.OpenText();
Your problem occurs, because you are not closing the stream readers.
A safer way of using external resources (the files in this case) is to embed their use in a using statement. The using statement automatically closes the resource at the end of the statement block or if the statement block if left in another way. This could be a return statement or an exception, for instance. It is guaranteed that the resource will be closed, even after an exception occurs.
You can apply the using statement on any object which implements the IDisposable interface.
// Writing to the files
using (var sw1 = new StreamWriter("DataNames.txt")) {
sw1.WriteLine(textBox1.Text);
}
using(var sw2 = new StreamWriter("DataNumbers.txt")) {
sw2.WriteLine(textBox2.Text);
}
// Reading from the files
FileInfo file1 = new FileInfo("DataNames.txt");
using (StreamReader sr1 = file1.OpenText()) {
while (!sr1.EndOfStream) {
listBox1.Items.Add(sr1.ReadLine());
}
}
FileInfo file2 = new FileInfo("DataNumbers.txt");
using (StreamReader sr2 = file2.OpenText()) {
while (!sr2.EndOfStream)
{
listBox2.Items.Add(sr2.ReadLine());
}
}
However, you can simplify the reading part like this
// Reading from the files
listBox1.Items.AddRange(File.ReadAllLines("DataNames.txt"));
listBox2.Items.AddRange(File.ReadAllLines("DataNumbers.txt"));
I've seen this behavior before - usually there's another process open that's blocking the file access. Do you have multiple development servers open in your taskbar? (Strange, yes, but I've seen it happen)
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)
{
...