How to clear a file before writing into it - c#

I am using this code to write into my file:
private async void play_Click(object sender, RoutedEventArgs e)
{
String MyScore;
Double previousScore = 0;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var dataFolder1 = await local.CreateFolderAsync("MyFolder", CreationCollisionOption.OpenIfExists);
var file1 = await dataFolder1.CreateFileAsync("MyFile.txt", CreationCollisionOption.OpenIfExists);
var file = await dataFolder1.OpenStreamForReadAsync("MyFile.txt");
using (StreamReader streamReader = new StreamReader(file))
{
MyScore = streamReader.ReadToEnd();
}
if (MyScore != null && !MyScore.Equals(""))
{
previousScore = Convert.ToDouble(MyScore);
}
Double CurerentScore = 0;
Double Total = 0;
String scoreText = this.ScoreTB.Text;
CurerentScore = Convert.ToDouble(scoreText);
Total = previousScore - CurerentScore;
using (var s = await file1.OpenStreamForWriteAsync())
{
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}
}
But before writing into it, I want that my file should get cleared. What should I do?
This is what i have tried so far but the problem is that it writes the file up to the filebytes.length and due to that if the new information to be writed in file is less in terms of length in comparison to the privous length then some garbage value or unnecessay thing comes after the end of the new file

You can use this snippet :
var folder = ApplicationData.Current.LocalFolder;
// You are going to replace the file
var file = await folder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
using (var stream = await file.OpenStreamForWriteAsync())
{
var content = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
await stream.WriteAsync(content, 0, content.Length);
}
To quote the documentation :
ReplaceExisting : Create the new file or folder with the desired name,
and replaces any file or folder that already exists with that name.

I have clear the file by writing a empty string to it and then i have written what i wanted in my file This solved my issue as nothing was there in the file so whatever i wanted to write to it came up successfully.

Simply use Stream.SetLength like this:
using (var s = await file1.OpenStreamForWriteAsync())
{
// Add this line
s.SetLength(0);
// Then write new bytes. use 's.SetLength(fileBytes.Length)' if needed.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(Convert.ToString(Total));
s.Write(fileBytes, 0, fileBytes.Length);
}

Related

Stream was not writeable (StreamWriter)

I'm trying to remove specific line from file on IsolatedStorage but I'm still receiving the "Stream was not writeable" from following method:
public async static void RemoveFavoriteFromFile(int id)
{
string favoriteFilename = Globals.FavoriteFilepath;
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.GetFolderAsync("DataFolder");
var file = await folder.OpenStreamForReadAsync(Globals.FavoriteFilepath);
using (StreamReader sr = new StreamReader(file))
{
using (StreamWriter sw = new StreamWriter(file))
{
string line = null;
while ((line = sr.ReadLine()) != null)
{
if (String.Compare(line, id.ToString()) == 0)
continue;
sw.WriteLine(line);
}
}
}
}
on line using (StreamWriter sw = new StreamWriter(file))
Could anybody help me please?
Thanks in advance
EDIT: I would mainly ask you to advice me how to remove specific line from existing file, no matter what I created already. Main issue for me in meaning of understanding is that how to write/edit a file which I firstly need to read for finding the specific line.
Reading and writing to the same file at the same time is always a bad idea.
Either write to a swap file "filename_swap.txt". After it has finished writing the entire file, delete the original file and rename the "filename_swap.txt" to the original file (basically replacing it).
Or you can read the entire file into a buffer, close the file. Make your changes to said buffer then open the file again for writing. This time, write the entire content of the modified buffer.
So lets modularize your program
using System.Threading.Tasks;
// read the specific file into a string buffer
private async Task<string> ReadFileIntoBuffer(string fileName)
{
string buffer = ""; // our buffer
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // local folder
var folder = await local.GetFolderAsync("DataFolder"); // sub folder
// open the file for reading
using (Stream s = await folder.OpenStreamForReadAsync(fileName))
{
using (StreamReader sr = new StreamReader(s))
{
buffer = await sr.ReadToEndAsync();
}
}
// return the buffer
return buffer;
}
// write the string buffer to a specific file
private async Task<bool> WriteBufferToFile(string fileName, string buffer)
{
try
{
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder; // local folder
var folder = await local.GetFolderAsync("DataFolder"); // sub folder
// open the file for writing
using (Stream s = await folder.OpenStreamForWriteAsync(fileName, CreationCollisionOption.ReplaceExisting))
{
using (StreamWriter sw = new StreamWriter(s))
{
await sw.WriteAsync(buffer);
}
}
}
catch (Exception ex)
{
string error_message = ex.Message;
return false;
}
return true;
}
// New Delete Lines function based off your old one
private string DeleteLines(string input_buffer, int id)
{
string output_buffer = "";
using (StringReader sr = new StringReader(input_buffer))
{
while (true)
{
string line = sr.ReadLine();
if (line != null)
{
if (String.Compare(line, id.ToString()) == 0)
{
}
else
{
// add it to the output_buffer plus the newline
output_buffer += (line + "\n");
}
}
else
{
break;
}
}
}
return output_buffer;
}
If you have trouble understanding a problem it generally a good idea to break it into smaller parts and debug from there.

Windows phone 8 append line to file

I have such strange problem with append line ... I'm quite new with developing for Windows phone, but I program¨m in c sharp for some time. So I tried to create file for saving users data (simple lines in txt file). I use this codes:
byte[] filebytes = System.Text.Encoding.UTF8.GetBytes("blablablabla");
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var folder = await local.CreateFolderAsync("Data", CreationCollisionOption.OpenIfExists);
var file = await folder.CreateFileAsync("data.txt", CreationCollisionOption.OpenIfExists);
using (var s = await file.OpenStreamForWriteAsync())
{
s.Write(filebytes, 0, filebytes.Length);
}
for writing to file and
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
if (local != null)
{
var folder = await local.GetFolderAsync("Data");
var file = await folder.OpenStreamForReadAsync("data.txt");
using (StreamReader sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
TextBlock.Text = line;
}
}
}
to read from it. I also tried many others possibility how to read/write to files, but all ended with the same result - all data lost, and in file was only last line. First I thought that problem will be in offset here s.Write(filebytes, 0, filebytes.Length); but in other methods it was in other way and nothing helped. Right now I have improved code, that it works, but read all data and write it all at once is not solution. Thanks for any advice.
Replace
s.Write(filebytes, 0, filebytes.Length);
With
await writer.WriteLineAsync("new entry");

Read files in WP8

i have a problem with reading file in WP8.
string text;
IStorageFolder applicationFolder = ApplicationData.Current.LocalFolder;
IStorageFile storageFile = await applicationFolder.GetFileAsync("MyFile.txt");
IRandomAccessStream accessStream = await storageFile.OpenReadAsync();
using (Stream stream = accessStream.AsStreamForRead((int)accessStream.Size))
{
byte[] content = new byte[stream.Length];
await stream.ReadAsync(content, 0, (int)stream.Length);
text = Encoding.UTF8.GetString(content, 0, content.Length);
}
return text;
Sometimes the storagefile or the accessStream crash without a reason.
If I debug them, it works.
I have no idea why. Can anyone help me?
I'm using this piece of code. The result will be the texts within your txt file, shortened into a string, so let's say your txt file contains this.
This
is
a test.
Result will be
This\nis\na\test.
Then, all you need to do is to split them up.
string result = null;
IsolatedStorageFile store = IsolatedStorageFile.GetUserStoreForApplication();
if (store.FileExists("services.txt"))
{
using (var stream = new IsolatedStorageFileStream("services.txt", FileMode.Open, store))
{
using (var fileReader = new StreamReader(stream))
{
result = fileReader.ReadToEnd();
}
}
}
This is how i split the message.
string[] tmp = result.Split(new char[] { '\r', '\n', '.' });
foreach (string str in tmp)
{
System.Diagnostics.Debug.WriteLine(str);
}
Hope this helps.

How to append a file, asynchronously in Windows Phone 8

I'm trying to append to a file in the latest Windows Phone. The problem is i'm trying to do everything asynchronously and i'm not sure how to do it.
private async void writeResult(double lat, double lng)
{
StorageFolder localFolder = ApplicationData.Current.LocalFolder;
StorageFile storageFile = await localFolder.CreateFileAsync("result.txt", CreationCollisionOption.OpenIfExists);
Stream writeStream = await storageFile.OpenStreamForWriteAsync();
using (StreamWriter writer = new StreamWriter(writeStream))
//using (StreamWriter sw = new StreamWriter("result.txt", true))
{
{
await writer.WriteLineAsync(lat + "," + lng);
//await sw.WriteLineAsync(lat + "," + lng);
writer.Close();
//sw.Close();
}
}
}
I have this so far, which writes to the file fine and I can read it later on much the same, however it writes over what I have instead of on a new line. The commented out lines show how to go about without the stream in WP7, but I can't get that to work either (the true is is the append flag) and really should be utilizing the new WP8 methods anyway.
Any comments appreciated
Easier way:
await Windows.Storage.FileIO.AppendTextAsync(storageFile, "Hello");
I used this code, works for me
private async System.Threading.Tasks.Task WriteToFile()
{
// Get the text data from the textbox.
byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes("Some Data to write\n".ToCharArray());
// Get the local folder.
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
// Create a new folder name DataFolder.
var dataFolder = await local.CreateFolderAsync("DataFolder",
CreationCollisionOption.OpenIfExists);
// Create a new file named DataFile.txt.
var file = await dataFolder.CreateFileAsync("DataFile.txt",
CreationCollisionOption.OpenIfExists);
// Write the data from the textbox.
using (var s = await file.OpenStreamForWriteAsync())
{
s.Seek(0, SeekOrigin.End);
s.Write(fileBytes, 0, fileBytes.Length);
}
}
I was able to use the suggestion ( Stream.Seek() ) by Oleh Nechytailo successfully

How to upload a file to a document library given a HttpPostedFile

I have a HttpPostedFile object and after the file gets uploaded locally onto the server, i want to move that temp file into a document library in sharepoint. Here is my code:
private void UploadWholeFile(HttpContext context, List<FilesStatus> statuses) {
for (int i = 0; i < context.Request.Files.Count; i++) {
HttpPostedFile file = context.Request.Files[i];
file.SaveAs(ingestPath + Path.GetFileName(file.FileName));
string fileName = Path.GetFileName(file.FileName);
}
Can anyone give me some example code for this? I have found a tutorial for Streams, but not quite sure if it would work the same in my situation
Replace the two lines starting with file.SaveAs with the following:
var myDocumentLibrary = SPContext.Current.Web.Folders["MyDocumentLibrary"];
var myFile = myDocumentLibrary.Files.Add(file.Name, file.FileContent, true);
I have a code sample for you that comes in parts:
Here is code that gets the Files content into a byte array buffer:
var file = (HttpPostedFileBase)Request.Files[0];
var buffer = new byte[file.ContentLength];
file.InputStream.Read(buffer, 0, file.ContentLength);
var root = HttpContext.Current.Server.MapPath(#"~/_temp");
var temp_file_name = "somefilename";
var path = Path.Combine(root, temp_file_name);
using (var fs = new FileStream(path, FileMode.Create))
{
using (var br = new BinaryWriter(fs))
{
br.Write(buffer);
}
}

Categories

Resources