Listbox-selecting items that are read from isolatedstorage - windows-phone-7

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

Related

Rename a recorded file every time I save a record in xamarin

I am saving my records using this code:
string path = Android.OS.Environment.ExternalStorageDirectory.AbsolutePath;
public string fileName { get; set; }
fileName = Path.Combine(path, "sample.wav");
if (!recorder.IsRecording)
{
recorder.StopRecordingOnSilence = TimeoutSwitch.IsToggled;
//Start recording
var audioRecordTask = await recorder.StartRecording();
BtnDoneRec.IsEnabled = false;
await audioRecordTask;
RecEditor.IsEnabled = true;
BtnDoneRec.IsEnabled = false;
PlayButton.IsEnabled = true;
var filePath = recorder.GetAudioFilePath();
if (filePath != null)
{
var stream = recorder.GetAudioFileStream();
using (var fileStream = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
}
else
{
//stop recording ...
await recorder.StopRecording();
}
I want my record to have a specific name which is labeled with my RecEditor
using (var streamReader = new StreamReader(fileName))
{
File.Move("sample.wav", RecEditor.Text + ".wav");
}
So it will rename "sample.wav" to "RecEditor text.wav" every time I click my save button.
But when I click save, it gives me this record
System.IO.FileNotFoundException: 'Could not find file '/sample.wav'.'
The record is stored in /storage/emulated/0/sample.wav
The sample.wav is created in my device but I don't know why it give me 'Could not find file '/sample.wav'.' error. What am i doing wrong here?
I believe that what you're looking is something like this:
if(File.Exists(fileName))
{
var newFileName = Path.Combine(path, $"{RecEditor.Text}.wav");
File.Move(fileName, newFileName);
}
You don't need to open a new Stream as you are doing. Also, you need to put the full file path not only the file name.
You might want to validate that RecEditor.Text is not empty before using its value for the newfileName
Hope this helps.-

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

Writing CSV to MemoryStream using LinqToCSV does not return any data

I've verified using System.Text.Encoding.ASCII.GetString(ms.ToArray)); that my memorystream has the expected data.
However using the LinqToCSV nuget library will not generate my csv file. I get no errors or exceptions thrown. I just get an empty file when I'm prompted to open the file.
Here is my Action Method
public FileStreamResult Export(){
var results = _service.GetProperties().Take(3);
System.IO.MemoryStream ms = new System.IO.MemoryStream();
System.IO.TextWriter txt = new System.IO.StreamWriter(ms);
CsvFileDescription inputFileDescription = new CsvFileDescription{
SeparatorChar =',',
FirstLineHasColumnNames = true
}
;
CsvContext csv = new CsvContext();
csv.Write(results,txt,inputFileDescription);
return File(ms , "application/x-excel");
}
I find it interesting, if I change the return type to contentResult, and the return method to Content() and pass it System.Text.Encoding.ASCII.GetString(ms.ToArray)); I do get a browser window showing my data.
Make sure you reset stream position to 0. Also make sure you flush your StreamWriter before that.
Calling the Web API method to return CVS file from JavaScript.
public HttpResponseMessage Bidreport([FromBody]int formData).....
Fill in your IEnumerable<YourObject>query = from LINQ query
....
This is how to return it:
using (var ms = new MemoryStream())
{
using (TextWriter txt = new StreamWriter(ms))
{
var cc = new CsvContext();
cc.Write(query, txt, outputFileDescription);
txt.Flush();
ms.Position = 0;
var fileData = Encoding.ASCII.GetString(ms.ToArray());
var result = new HttpResponseMessage(HttpStatusCode.OK) {Content = new StringContent(fileData)};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/x-excel");
return result;
}
}

windows phone 7 updating isolated storage

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

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