what will happen if file not exist - c#

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.

Related

"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();
}
}

Isolated storage operation not permitted on IsolatedStorageFileStream all of a sudden [duplicate]

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.

windows phone 7 isolated storage - operation not permitted

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.

Writing data from textbox into text file

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)

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