Windows Phone C# -loading from text files - c#

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.

Related

FileMode and FileAccess and IOException: The process cannot access the file 'filename' because it is being used by another process

I have an application A that generates a text file for tracing.
While, an application B needs read the same text file and attach in a mailmessage.
But I get the following error, when application B try read the text file:
IOException: The process cannot access the file 'filename' because it
is being used by another process
Any suggestions ? Maybe better use for FileMode and FileAccess?
Application A
if (File.Exists(nFile2)) File.Delete(nFile2);
traceFile2 = File.Open(nFile2, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);
if (traceFile2 != null)
{
var twt2 = new TextWriterTraceListener(traceFile2);
// http://www.helixoft.com/blog/archives/20
try
{
if (twt2.Writer is StreamWriter)
{
(twt2.Writer as StreamWriter).AutoFlush = true;
}
}
catch { }
var indiceTraceFile2 = Trace.Listeners.Add(twt2);
System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());
Application B
using (FileStream fileStream = File.Open(f, FileMode.Open, FileAccess.ReadWrite, FileShare.Read))
{
var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
msgMail.Attachments.Add(messageAttachment);
}
You need to make sure that both the service and the reader open the log file non-exclusively. Notice line 2 of App A and Line 1 of App B
Application A:
if (File.Exists(nFile2))
File.Delete(nFile2);
traceFile2 = new FileStream(nFile2, FileMode.Open, FileAccess.Write, FileShare.ReadWrite);
if (traceFile2 != null)
{
var twt2 = new TextWriterTraceListener(traceFile2);
// http://www.helixoft.com/blog/archives/20
try
{
if (twt2.Writer is StreamWriter)
{
(twt2.Writer as StreamWriter).AutoFlush = true;
}
}
catch { }
var indiceTraceFile2 = Trace.Listeners.Add(twt2);
System.Diagnostics.Trace.WriteLine("INICIO: " + DateTime.Now.ToString());
and Application B:
using (FileStream fileStream = new FileStream(f, FileMode.Open,
FileAccess.Read,
FileShare.ReadWrite))
{
var messageAttachment = new Attachment(fileStream, Path.GetFileName(f));
msgMail.Attachments.Add(messageAttachment);
}
Of course you can read and write from/to the same file at the same time (by different threads/processes).
Here is a sample code. Just see how FileStream is created.
string fname = "a.txt";
//WRITER
Task.Factory.StartNew(() =>
{
var f = new FileStream(fname, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite);
var s = new StreamWriter(f);
long l = 0;
while (true)
{
s.WriteLine(l++);
s.Flush();
Task.Delay(1000).Wait();
}
});
//READER
Task.Factory.StartNew(() =>
{
Task.Delay(1000).Wait();
var f = new FileStream(fname, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
var s = new StreamReader(f);
while (true)
{
var line = s.ReadLine();
if (line == null) { Task.Delay(100).Wait(); continue; };
Console.WriteLine("> " + line + " <");
}
});
It seems that you are not using the Dispose() and Close() methods of StreamWriter class to release the file.
You need to release control of the file from Program A. Try closing or disposing the streamwriter when you finish.
Or you might attempt using as is described in the answer to this question: Releasing access to files

WIndows Phone 7 reading file to String

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;

Searching for string using OpenFileDialog and Multiselect

I am doing an exercise where I need to find a string in a group of files.
I manage to find the string selecting each file individually.
How can I do the same selecting all files at once.
openFileDialog.Multiselect = true;
DialogResult result = openFileDialog.ShowDialog();
string filename = openFileDialog.SafeFileName;
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BufferedStream bs = new BufferedStream(fs);
StreamReader sr = new StreamReader(fs);
String s;
if (result == DialogResult.OK)
{
while ((s = sr.ReadLine()) != null)
{
if(s.Contains("Specified string"))
{
MessageBox.Show(filename + " Contains the Specified string");
break;
}
}
}
fs.Close();
sr.Close();
OpenFileDialog has properties (FileNames, SafeFileNames) that return all selected files.
First of all, you should use SafeFileNames Property:
if (result == DialogResult.OK)
{
foreach(string filename = openFileDialog.SafeFileName)
{
FileStream fs = new FileStream(filename, FileMode.Open, FileAccess.Read);
BufferedStream bs = new BufferedStream(fs);
StreamReader sr = new StreamReader(fs);
String s;
while ((s = sr.ReadLine()) != null)
{
if(s.Contains("Specified string"))
{
MessageBox.Show(filename + " Contains the Specified string");
break;
}
}
fs.Close();
sr.Close();
}
}
For second, you can use Parallel Class for simultaneous processing of the files.

Writing to isolated storage in windows phone 7

I am trying to read from the isolated storage if the file is exist it will delete the whole file and directories before recreating the file.
Then if the file does not exist it will create the file and directories.
Below is my code: I got a error of opertion not permitted on isolated storage at write file
int indexQues;
string rate;
string[] queSplit;
string[] rateSplit;
private void saveBtn_Click(object sender, RoutedEventArgs e)
{
indexQues = queListPicker.SelectedIndex;
rate = rateListPicker.SelectedItem.ToString();
IsolatedStorageFile myStore = IsolatedStorageFile.GetUserStoreForApplication();
try
{
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
String queText = readFileQue.ReadLine();
queSplit = queText.Split(new char[] { '^' });
String rateText = readFileRate.ReadLine();
rateSplit = rateText.Split(new char[] { '^' });
readFileQue.Close();
readFileRate.Close();
int noOfQueInDB = queSplit.Count();
int noOfRateInDB = rateSplit.Count();
MessageBox.Show(noOfQueInDB.ToString());
//if (noOfQueInDB == 2)
//{
myStore.DeleteFile("SettingFolder\\queSetting.txt");
myStore.DeleteFile("SettingFolder\\rateSetting.txt");
myStore.DeleteDirectory("SettingFolder");
MessageBox.Show("Deleted all");
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
//}
}
catch (Exception)
{
myStore.CreateDirectory("SettingFolder");
//Retrieve the content of "noOfQues"
//And write it into queSetting.txt
// ****
// **** The following line throws an exception
// ****
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Create, myStore));
writeFile.Write(indexQues);
// writeFile.Write("^" + indexQues);
writeFile.Close();
StreamWriter writeFile1 = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt", FileMode.Create, myStore));
writeFile1.Write(rate);
writeFile1.Close();
MessageBox.Show("Setting Saved");
MessageBox.Show(indexQues.ToString());
MessageBox.Show(rate);
NavigationService.Navigate(new Uri("/MainPage.xaml", UriKind.Relative));
}
}
one point - this seems wrong (you open the same file twice ?):
//For question
StreamReader readFileQue = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
//For passing rate
StreamReader readFileRate = new StreamReader(new IsolatedStorageFileStream("SettingFolder\\queSetting.txt", FileMode.Open, myStore));
second point - you should use Dispose:
readFileQue.Close(); readFileQue.Dispose(); readFileQue = null;
readFileRate.Close(); readFileRate.Dispose(); readFileRate = null;
third point - user proper FileAccess when creating the files:
StreamWriter writeFile = new StreamWriter(new IsolatedStorageFileStream("SettingFolder\\rateSetting.txt",
FileMode.Create,
FileAccess.Write,
FileShare.Write,
myStore);
Hope the above helps... if not check whether the Directory is really created...
EDIT:
Are you sure the Exception is thrown from the catch-block ? IF so, then there must have happened some Exception before that - what was that Exception?

Reading file content changes in .NET

In Linux, a lot of IPC is done by appending to a file in 1 process and reading the new content from another process.
I want to do the above in Windows/.NET (Too messy to use normal IPC such as pipes). I'm appending to a file from a Python process, and I want to read the changes and ONLY the changes each time FileSystemWatcher reports an event. I do not want to read the entire file content into memory each time I'm looking for changes (the file will be huge)
Each append operation appends a row of data that starts with a unique incrementing counter (timestamp+key) and ends with a newline.
using (FileStream fs = new FileStream
(fileName, FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
{
using (StreamReader sr = new StreamReader(fs))
{
while (someCondition)
{
while (!sr.EndOfStream)
ProcessLinr(sr.ReadLine());
while (sr.EndOfStream)
Thread.Sleep(100);
ProcessLinr(sr.ReadLine());
}
}
}
this will help you read only appended lines
You can store the offset of the last read operation and seek the file to that offset when you get a changed file notification. An example follows:
Main method:
public static void Main(string[] args)
{
File.WriteAllLines("test.txt", new string[] { });
new Thread(() => ReadFromFile()).Start();
WriteToFile();
}
Read from file method:
private static void ReadFromFile()
{
long offset = 0;
FileSystemWatcher fsw = new FileSystemWatcher
{
Path = Environment.CurrentDirectory,
Filter = "test.txt"
};
FileStream file = File.Open(
"test.txt",
FileMode.Open,
FileAccess.Read,
FileShare.Write);
StreamReader reader = new StreamReader(file);
while (true)
{
fsw.WaitForChanged(WatcherChangeTypes.Changed);
file.Seek(offset, SeekOrigin.Begin);
if (!reader.EndOfStream)
{
do
{
Console.WriteLine(reader.ReadLine());
} while (!reader.EndOfStream);
offset = file.Position;
}
}
}
Write to file method:
private static void WriteToFile()
{
for (int i = 0; i < 100; i++)
{
FileStream writeFile = File.Open(
"test.txt",
FileMode.Append,
FileAccess.Write,
FileShare.Read);
using (FileStream file = writeFile)
{
using (StreamWriter sw = new StreamWriter(file))
{
sw.WriteLine(i);
Thread.Sleep(100);
}
}
}
}

Categories

Resources