windows phone 7 updating isolated storage - windows-phone-7

In windows phone 7, what is the protocol for updated an isolated storage text file? Say I have 10 words in a text file arranged at 1 per line. Now suppose, the user uses the application and a new word needs to be stored on the fifth line. How do I write to the file, which already contains 10 words with 1 word per line?
Thanks in advance you guys are awesome.

The way I have been doing it is:
Read in a file from IsolatedStorage to menmory
Update the String
Write the file back to storage
Read in File
public static string ReadFromStorage(string filename)
{
string fileText = "";
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream(filename, FileMode.Open, storage)))
{
fileText = sr.ReadToEnd();
}
}
}
catch
{
}
return fileText;
}
Write to File
public static void WriteToStorage(string filename, string text)
{
try
{
using (IsolatedStorageFile storage = IsolatedStorageFile.GetUserStoreForApplication())
{
string directory = Path.GetDirectoryName(filename);
if (!storage.DirectoryExists(directory))
storage.CreateDirectory(directory);
if (storage.FileExists(filename))
{
MessageBoxResult result = MessageBox.Show(filename + " Exists\nOverwrite Existing File?", "Question", MessageBoxButton.OKCancel);
if (result == MessageBoxResult.Cancel)
return;
}
using (StreamWriter sw = new StreamWriter(storage.CreateFile(filename)))
{
sw.Write(text);
}
}
}
catch
{
}
}
So I would do:
string fileName = "Test.txt";
string testFile = IsolatedStorage_Utility.ReadFromStorage(fileName);
testFile = testFile.Replace("a", "b");
IsolatedStorage_Utility.WriteToStorage(fileName, testFile);

Writing to a file in Isolated Storage is basically a file write operation. It is similar as how you will access a normal file and read write to it in normal operating system. in your scenario if you are sure that you need to update 5th line out of 10 lines, you will read line by line using stream reader and will use stream writer to update the specific line that you want to update. You do not need to re-write all content again and again.
On the other hand if you just want to add new content you can just append it to end of file. You may find this link useful http://goo.gl/IKii5

Related

Slash xamarin issue

I am trying to get values from a specified route to load it in a collectionView. I don't know why Xamarin add a / to my path at the beggining. I am desesperate, I've tried to replace the /, differents ways to obtain the path, in differents places (inside the project, in the desktop) and any works. I think the problem could be the MonoAndroid file or some dll but I am not sure.
Differents things I've tried:
1:
StreamReader sr = new StreamReader("./ficheroPruebaXautoCB.txt");
string linea;
// Read the file and display it line by line.
while ((linea = sr.ReadLine()) != null)
{
ubicaciones.Ubication = linea.Substring(27, 33);
ubicaciones.Values = linea.Substring(0, 26) + linea.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
sr.Close();
2:
string path = "F:\\Xamarin\\Pruebas_fichero\\ficheroPruebaXautoCB.txt";
string path2 = #"F:\Xamarin\Pruebas_fichero\ficheroPruebaXautoCB.txt";
foreach (string line in System.IO.File.ReadLines(path2))
{
ubicaciones.Ubication = line.Substring(27, 33);
ubicaciones.Values = line.Substring(0, 26) + line.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
3:
string nombreArchivo = "ficheroPruebaXautoCB.txt";
string ruta = Environment.GetFolderPath(Environment.SpecialFolder.ProgramFiles);
string rutaCompleta = Path.Combine(ruta, nombreArchivo);
if (File.Exists(rutaCompleta))
{
using (var lector = new StreamReader(rutaCompleta, true))
{
string textoLeido;
while ((textoLeido = lector.ReadLine()) != null)
{
ubicaciones.Ubication = textoLeido.Substring(27, 33);
ubicaciones.Values = textoLeido.Substring(0, 26) + textoLeido.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
counter++;
}
}
}
4:
string ruta = "C:\\Users\\H_L\\Desktop\\ficheroPruebaXautoCB.txt";
try
{
//FileStream f = File.OpenRead(ruta);
var text = File.ReadLines(ruta, Encoding.UTF8);
foreach (string line in text)
{
ubicaciones.Ubication = line.Substring(27, 33);
ubicaciones.Values = line.Substring(0, 26) + line.Substring(34, 48);
listUbicaciones.Add(ubicaciones);
}
}
catch (IOException e)
{
Console.WriteLine(e.Message);
}
And the error:
"Could not find file "/C:\Users\H_L\Desktop\ficheroPruebaXautoCB.txt""
All these solutions have worked in a console C# project, so the problem is when I try to do it with Xamarin.
It seems that you can't access the file in your pc with the path for the android. You need to provide a path which the Android can use.
At first, you need to copy the local file into the simulator. You can check the following link : How to access local files of the filesystem in the Android emulator?
And then, if the file is in the app's own folder, you can access it without any storage permission. But when the file is in the other folders, you need to grant the read and write storage permission to your app.
You can check my old answer in the following link:How to open SQLite DB created by one Xamarin Android app in another app?

FSDataOutputStream.writeUTF() adds extra characters at the start of the data on hdfs. How to avoid this extra data?

What I am trying to is to convert a sequence file on hdfs which has xml data into .xml files on hdfs.
Searched on Google and found the below code. I made modifications according to my need and the following is the code..
public class SeqFileWriterCls {
public static void main(String args[]) throws Exception {
System.out.println("Reading Sequence File");
Path path = new Path("seq_file_path/seq_file.seq");
Configuration conf = new Configuration();
FileSystem fs = FileSystem.get(conf);
SequenceFile.Writer writer = null;
SequenceFile.Reader reader = null;
FSDataOutputStream fwriter = null;
OutputStream fowriter = null;
try {
reader = new SequenceFile.Reader(fs, path, conf);
//writer = new SequenceFile.Writer(fs, conf,out_path,Text.class,Text.class);
Writable key = (Writable) ReflectionUtils.newInstance(reader.getKeyClass(), conf);
Writable value = (Writable) ReflectionUtils.newInstance(reader.getValueClass(), conf);
while (reader.next(key, value)) {
//i am just editing the path in such a way that key will be my filename and data in it will be the value
Path out_path = new Path(""+key);
String string_path = out_path.toString();
String clear_path=string_path.substring(string_path.lastIndexOf("/")+1);
Path finalout_path = new Path("path"+clear_path);
System.out.println("the final path is "+finalout_path);
fwriter = fs.create(finalout_path);
fwriter.writeUTF(value.toString());
fwriter.close();
FSDataInputStream in = fs.open(finalout_path);
String s = in.readUTF();
System.out.println("file has: -" + s);
//fowriter = fs.create(finalout_path);
//fowriter.write(value.toString());
System.out.println(key + " <===> :" + value.toString());
System.exit(0);
}
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeStream(reader);
fs.close();
}
}
I am using "FSDataOutputStream" to write the data to HDFS and the method is used is "writeUTF" The issue is that when i write to the hdfs file some additional characters are getting in the starting of data. But when i print the data i couldnt see the extra characters.
i tried using writeChars() but even taht wont work.
is there any way to avoid this?? or is there any other way to write the data to HDFS???
please help...
The JavaDoc of the writeUTF(String str) method says the followings:
Writes a string to the underlying output stream using modified UTF-8 encoding in a machine-independent manner.
First, two bytes are written to the output stream as if by the writeShort method giving the number of bytes to follow. This value is the number of bytes actually written out, not the length of the string. Following the length, each character of the string is output, in sequence, using the modified UTF-8 encoding for the character. (...)
Both the writeBytes(String str) and writeChars(String str) methods should work fine.

How to display file names from isolated storage in a listbox?

I'm developing a app where i have to display filenames in a listbox, files are created by the user and are stored in a directory created using isolated storage. i'm new to windows phone programming. i'm not finding enough resources for isolated storage file access??? Plzzz help
Code for Binding to the list:
private void bindList()
{
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
string[] fileList = appStorage.GetFileNames("/NotesForBible");
listPicker1.ItemsSource = fileList;
}
COde for adding the file:
{
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
appStorage.CreateDirectory("NotesForBible");
if (!appStorage.FileExists(fileName))
{
using (var file = appStorage.CreateFile("NotesForBible/" + fileName ))
{
using (var writer = new StreamWriter(file))
{
writer.WriteLine(fileContent);
}
}
}
I'm not able to view the files created in the listbox
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
To get an array of all filenames:
string directory = "whatever";
string[] filenames = store.GetFileNames(directory);
For further information: http://msdn.microsoft.com/en-us/library/system.io.isolatedstorage.isolatedstoragefile.aspx

Listbox-selecting items that are read from isolatedstorage

Ok, here is a simple code, that will explain what i need to do:
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
StreamWriter writeFile;
if (!store.DirectoryExists("SaveFolder"))
{
store.CreateDirectory("SaveFolder");
writeFile = new StreamWriter(new IsolatedStorageFileStream("SaveFolder\\SavedFile.txt", FileMode.CreateNew, store));
}
else
{
writeFile = new StreamWriter(new IsolatedStorageFileStream("SaveFolder\\SavedFile.txt", FileMode.Append, store));
}
StringWriter str = new StringWriter();
str.Write(urlHolder.Text);
writeFile.WriteLine(str.ToString());
writeFile.Close();
So, i have a isolatedstorage where i keep some links, that are read from some textbox(urlHolder), on the other side, i read those links and put them in listbox:
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
StreamReader readFile = null;
try
{
readFile = new StreamReader(new IsolatedStorageFileStream("SaveFolder\\SavedFile.txt", FileMode.Open, store));
string fileText = readFile.ReadToEnd();
bookmarkListBox.Items.Add(fileText);
readFile.Close();
}
catch
{
MessageBox.Show("Need to create directory and the file first.");
}
The thing with writing and reading is ok, but the problem is when that links are in listbox, when i want to select one of them it selects all of them...i tried everything, but no result, so, if anyone knows some solution, please write...Thanks!
You're reading the whole file as a single string and then adding it as a single item in the ListBox.
You need to add the lines/links as separate items. Try something like:
while (var item = readFile.ReadLine())
{
bookmarkListBox.Items.Add(item);
}

Open a project file in phone7

Howdy,
I have a project in VisualStudio which contains a folder 'xmlfiles' below the root node. This folder contains a file 'mensen.xml' which I try to open ...
However when I try to open that very file the debugger steps in and throws an exception.
I tried it with
if(File.Exists(#"/xmlfiles/mensen.xml") )
{
bool exists = true;
}
as well as:
FileStream fs = File.Open("/xmlfiles/mensen.xml", FileMode.Open);
TextReader textReader = new StreamReader(fs);
kantinen = (meineKantinen)deserializer.Deserialize(textReader);
textReader.Close();
Nothin is working :(.
How can I open a local file in the Phone7 Emulator?
If you are just opening it to read it then you can do the following (Assuming you have set the Build Action of the file to Resource):
System.IO.Stream myFileStream = Application.GetResourceStream(new Uri(#"/YOURASSEMBLY;component/xmlfiles/mensen.xml",UriKind.Relative)).Stream;
If you are attempting to read/write this file then you will need to copy it to Isolated Storage. (Be sure to add using System.IO.IsolatedStorage)
You can use these methods to do so:
private void CopyFromContentToStorage(String fileName)
{
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
System.IO.Stream src = Application.GetResourceStream(new Uri(#"/YOURASSEMBLY;component/" + fileName,UriKind.Relative)).Stream;
IsolatedStorageFileStream dest = new IsolatedStorageFileStream(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write, store);
src.Position = 0;
CopyStream(src, dest);
dest.Flush();
dest.Close();
src.Close();
dest.Dispose();
}
private static void CopyStream(System.IO.Stream input, IsolatedStorageFileStream output)
{
byte[] buffer = new byte[32768];
long TempPos = input.Position;
int readCount;
do
{
readCount = input.Read(buffer, 0, buffer.Length);
if (readCount > 0) { output.Write(buffer, 0, readCount); }
} while (readCount > 0);
input.Position = TempPos;
}
In both cases, be sure the file is set to Resource and you replace the YOURASSEMBLY part with the name of your assembly.
Using the above methods, to access your file just do this:
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (!store.FileExists(fileName))
{
CopyFromContentToStorage(fileName);
}
store.OpenFile(fileName, System.IO.FileMode.Append);
The emulator does not have access to the PC file system. You must deploy the file to the target (emulator). The easiest way to do this is mark the file as an embedded Resource. Set the file's Build Action to 'Resource' and then extract it at runtime with code something like this:
var res = Application.GetResourceStream(new Uri([nameOfYourFile], UriKind.Relative))

Resources