Invalid Operation Exception in file saving - c#

I have this code and I don't know why it pops up this error message :
"Invalid Operation Exception was unhandled by user code".
This error comes out when I press the save button.
The purpose of this program is to save the text from one textbox in the Mytest.txt file and then from the file to the textbox1. I would really appreciate some help here.
Thank you in advance.
public MainPage()
{
this.InitializeComponent();
}
private void buttonsave_Click(object sender, RoutedEventArgs e)
{
string path = #"C:\Users\geora\Mytest.txt";
if(!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine(textBox.Text);
}
}
}
private void buttonshow_Click(object sender, RoutedEventArgs e)
{
string path = #"C:\Users\geora\Mytest.txt";
using (StreamReader sr = File.OpenText(path))
{
string s = "";
s = sr.ReadLine();
textBox1.Text = s;
}
}

You have opened files but not closed the file.This Might be the issue
StreamReader sr = File.OpenText(path)
You need to close it. Using does this for you (and disposes it so it's GC'd sooner):
Or alternatively in .Net 2 you can use the new File. static members, then you don't need to close anything:
variable = File.ReadAllText(path);

Additional to your exception
WPF Version:
private void loadButton_Click(object sender, RoutedEventArgs e)
{
try
{
textBox.Text = File.ReadAllText(#"d:\test.txt");
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
private void saveButton_Click(object sender, RoutedEventArgs e)
{
try
{
File.WriteAllText(#"d:\test.txt", textBox.Text);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString());
}
}
UWP Version:
using System;
using Windows.Storage;
using Windows.UI.Popups;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
...
private async void buttonSave_Click(object sender, RoutedEventArgs e)
{
try
{
var storageFolder = ApplicationData.Current.LocalFolder;
var sampleFile = await storageFolder.CreateFileAsync("sample.txt",
CreationCollisionOption.ReplaceExisting);
await FileIO.WriteTextAsync(sampleFile, textBox.Text);
var msgbox = new MessageDialog(sampleFile.Path, "Your file is in");
await msgbox.ShowAsync();
}
catch (Exception ex)
{
var msgbox = new MessageDialog(ex.ToString(), "Error");
await msgbox.ShowAsync();
}
}
private async void buttonLoad_Click(object sender, RoutedEventArgs e)
{
try
{
var storageFolder = ApplicationData.Current.LocalFolder;
var sampleFile = await storageFolder.GetFileAsync("sample.txt");
textBox.Text = await FileIO.ReadTextAsync(sampleFile);
}
catch (Exception ex)
{
var msgbox = new MessageDialog(ex.ToString(), "Error");
await msgbox.ShowAsync();
}
}

Related

when to use await key word? do I need it in this case?

i have a onClick method on a buttom. when this button is pressed, i get a displayalert message.
getTokenQ has a value. my question why its going inside catch block?
private async void Button_Clicked(object sender, EventArgs e)
{
try
{
var getTokenQ = await SecureStorage.GetAsync("Save_Security_Question");
if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
{
}
else
{
}
}
catch (Exception ex)
{
await DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
}
}
no you don't need to do that, you can use .Result if you don't want to execute your code asynchronously , this code is perfectly fine :
private void Button_Clicked(object sender, EventArgs e)
{
try
{
var getTokenQ = SecureStorage.GetAsync("Save_Security_Question").Result;
if ((String.IsNullOrWhiteSpace(getTokenQ) == false))
{
}
else
{
}
}
catch (Exception ex)
{
DisplayAlert("Message", "Some thing went wrong. Please try different method", "ok");
}
}
Why in catch ! Because it's a message to display only if an exception is thrown.

BackgroundWorker's progress bar is not working

The BackgroundWorker's progressbar is not updated while doing some tasks. What I would like to reach is progressbar moving while iterating through each file in DirectoryInfo. Suppose we have 20 files of ".sql" while first file completed it should be 5%, 10% and etc.
Here is my code.
private void CSV_Click(object sender, RoutedEventArgs e)
{
try
{
btnExtract.IsEnabled = false;
workerextract.RunWorkerAsync();
}
catch (Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
private void workerextract_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
this.Dispatcher.Invoke(() =>
{
DirectoryInfo di = new DirectoryInfo(txtQueryfolder.Text);
files = di.GetFiles("*.sql").Count();
currentfile = 0;
foreach (FileInfo fi in di.GetFiles("*.sql"))
{
// Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(fi.FullName))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
//System.Windows.MessageBox.Show(line);
ExtractToCSV(line, System.IO.Path.GetFileNameWithoutExtension(fi.Name));
currentfile++;
}
int percentage = (currentfile + 1) * 100 / files;
workerextract.ReportProgress(percentage);
}
});
}
catch(Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
private void workerextract_ProgressChanged(object sender, System.ComponentModel.ProgressChangedEventArgs e)
{
progressBarExtract.Value = e.ProgressPercentage;
}
private void workerextract_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
btnExtract.IsEnabled = true;
System.Windows.MessageBox.Show("CSV Data extraction finished!");
}
I found that
private void workerextract_ProgressChanged(object sender,
System.ComponentModel.ProgressChangedEventArgs e)
is called once at the end when 100%.
Also,
private void workerextract_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
never called as I do not see Message Box at the end.
So, I think I am doing something wrong here, could you please direct me on right way?
The problem was in wrapping whole DoWork inside Dispatcher.Invoke.
I need to wrap only those code where it is interacting with UI.
So I changed the code appropriately and it works.
private void workerextract_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
try
{
this.Dispatcher.Invoke(() =>
{
di = new DirectoryInfo(txtQueryfolder.Text);
});
files = di.GetFiles("*.sql").Count();
currentfile = 0;
foreach (FileInfo fi in di.GetFiles("*.sql"))
{
// Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(fi.FullName))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
this.Dispatcher.Invoke(() =>
{
//System.Windows.MessageBox.Show(line);
ExtractToCSV(line, System.IO.Path.GetFileNameWithoutExtension(fi.Name));
});
currentfile++;
}
int percentage = (currentfile + 1) * 100 / files;
workerextract.ReportProgress(percentage);
}
}
catch(Exception ex)
{
System.Windows.MessageBox.Show(ex.Message);
}
}
Thanks to all for showing the direction.
Using this.Dispatcher.Invoke in the BackgroundWorker's DoWork event you are executing the whole operation in the UI thread; which is what BackgroundWorker born to avoid to do.
Also, you get an error unwrapping your code from the dispatcher because you are accessing an UI object, which is txtQueryfolder.
Just use:
private void workerextract_DoWork(object sender, System.ComponentModel.DoWorkEventArgs e)
{
string queryFolder = e.Argument.ToString();
try
{
DirectoryInfo di = new DirectoryInfo(queryFolder);
files = di.GetFiles("*.sql").Count();
currentfile = 0;
foreach (FileInfo fi in di.GetFiles("*.sql"))
{
// Open the text file using a stream reader.
using (StreamReader sr = new StreamReader(fi.FullName))
{
// Read the stream to a string, and write the string to the console.
string line = sr.ReadToEnd();
//System.Windows.MessageBox.Show(line);
// ExtractToCSV shouldn't access to a UI object.
ExtractToCSV(line, System.IO.Path.GetFileNameWithoutExtension(fi.Name));
currentfile++;
}
int percentage = (currentfile + 1) * 100 / files;
workerextract.ReportProgress(percentage);
}
}
catch (Exception ex)
{
// Don't use MessageBox in a thread different from the UI one. Just set the result (e.Result) and get that in the RunWorkerCompleted event.
// System.Windows.MessageBox.Show(ex.Message);
}
}
When you call the RunWorkerAsync method just add the parameter like below:
workerextrac.RunWorkerAsync(txtQueryfolder.Text);

File I/O Exceptions

i am currently working on a Windows Forms App in c# which will allow the user to add or delete records. when i hit the button to display all the records written to the file the files appear, but when i try to delete by transact number i get an exception saying that "The process cannot access the the because it is being used somewhere else". i have tried putting it in a try-catch block to make sure the reader/writer will close and still not working code will be attached any help is greatly appreciated. p.s im not looking for code to finish this project just help getting by this exception and make it work like it is suppose.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace MMFileIO
{
public partial class MMAssignment3 : Form
{
StreamWriter writer;
StreamReader reader;
string record = "";
public MMAssignment3()
{
InitializeComponent();
}
private void MMAssignment3_Load(object sender, EventArgs e)
{
txtFile.Text = #"c:\burnable\assignment3.txt";
if (!Directory.Exists(txtFile.Text.Substring
(0, txtFile.Text.LastIndexOf('\\'))))
MessageBox.Show("File path does not exist");
}
private void btnAdd_Click(object sender, EventArgs e)
{
try
{
if (radNew.Checked)
writer = new StreamWriter(txtFile.Text, append: false);
else
writer = new StreamWriter(txtFile.Text, append: true);
}
catch(Exception ex)
{
if (writer != null)
writer.Close();
MessageBox.Show($"exception adding new record: {ex.Message}");
return;
}
record = $"{txtTransact.Text}::{txtDate.Text}::{txtSerial.Text}::" +
$"{txtToolPurchased.Text}::${txtPrice.Text}::{txtQty.Text}::" +
$"${txtAmount.Text}";
try
{
writer.WriteLine(record);
lblMessage.Text = ($"Record added");
txtTransact.Text = txtDate.Text = txtSerial.Text =
txtToolPurchased.Text = txtPrice.Text = txtQty.Text =
txtAmount.Text = "";
}
catch(Exception ex)
{
MessageBox.Show($"exception adding a new record: {ex.Message}");
}
finally
{
writer.Close();
}
}
private void btnDelete_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
List<string> records = new List<string>();
while (! reader.EndOfStream)
{
record = reader.ReadLine();
records.Add(record);
}
if (records.Count == 0)
MessageBox.Show("No records left in file");
reader.Close();
writer = new StreamWriter(txtFile.Text, append: false);
foreach (string item in records)
{
}
}
private void btnCloseFile_Click(object sender, EventArgs e)
{
txtDataDisplay.Text = "";
reader.Close();
}
private void btnDisplay_Click(object sender, EventArgs e)
{
reader = new StreamReader(txtFile.Text);
txtDataDisplay.Text = $"{"#".PadRight(10)}\t" +
$"{"Purchase-Date".PadRight(10)}\t{"Serial #".PadRight(10)}\t" +
$"{"Manufacturing Tools".PadRight(10)}\t{"Price".PadRight(10)}\t" +
$"{"Qty".PadRight(10)}\t{"Amount".PadRight(10)}\n{"".PadRight(50)}\n";
while (!reader.EndOfStream)
{
record = reader.ReadLine();
string[] fields = record.Split(new string[] { "::" }, StringSplitOptions.None);
txtDataDisplay.Text += $"{fields[0].PadRight(10)}\t" +
$"{fields[1].PadRight(10)}\t{fields[2].PadRight(10)}\t" +
$"{fields[3].PadRight(30)}\t{fields[4].PadRight(10)}\t" +
$"{fields[5].PadRight(10)}\t{fields[6].PadRight(10)}\n";
}
reader.Close();
}

uploadfile windows form C# web service

i'm new here,
help me out here please,
i am working with web service and doing upload file.
here's my code for uploading file
private void Button_Click(object sender, RoutedEventArgs e)
{
testServiceClient = new TestServiceClient();
var uploadFile = "C:\\Computer1\\Sample.csv";
try
{
var dir = #"\\Computer2\UploadedFile\";
string myUploadPath = dir;
var myFileName = Path.GetFileName(uploadFile);
var client = new WebClient { Credentials = CredentialCache.DefaultNetworkCredentials };
client.UploadFile(myUploadPath + myFileName, "PUT", uploadFile);
client.Dispose();
MessageBox.Show("ok");
testServiceClient.Close();
}
catch (Exception ex)
{
ex.ToString();
}
}
i can upload file in the same network, but my question is this,
how can i upload file when the two computer is not in the same network?
i've tried changing the
var dir = #"\\Computer2\UploadedFile\";
to
var dir = #"https://Computer2/UploadedFile/";
but i'm getting an error 'unable to connect to remote server'
help me out here pls.
In windows:
private void uploadButton_Click(object sender, EventArgs e)
{
var openFileDialog = new OpenFileDialog();
var dialogResult = openFileDialog.ShowDialog();
if (dialogResult != DialogResult.OK) return;
Upload(openFileDialog.FileName);
}
private void Upload(string fileName)
{
var client = new WebClient();
var uri = new Uri("https://Computer2/UploadedFile/");
try
{
client.Headers.Add("fileName", System.IO.Path.GetFileName(fileName));
var data = System.IO.File.ReadAllBytes(fileName);
client.UploadDataAsync(uri, data);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
In server:
[HttpPost]
public async Task<object> UploadedFile()
{
var file = await Request.Content.ReadAsByteArrayAsync();
var fileName = Request.Headers.GetValues("fileName").FirstOrDefault();
var filePath = "/upload/files/";
try
{
File.WriteAllBytes(HttpContext.Current.Server.MapPath(filePath) + fileName, file);
}
catch (Exception ex)
{
// ignored
}
return null;
}
I think the problem is that you are not actually sending the file with your UploadFile() method, you are just sending the file path. you should be sending the file bytes.
This link is quite usefull: http://www.codeproject.com/Articles/22985/Upload-Any-File-Type-through-a-Web-Service

How delete file in localstorage on winrt?

i try whithout success to delete a file in my local storage. Exactly, i took a photo and i want to delete it later with a button for exemple. But when i click on the button, the app bugs and i have : "access denied".
I sude a simple Delet.Async() after i get the file in a StorageFile.
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
}
Try the code below to see if it works for you.
private async void takephoto_click(object sender, RoutedEventArgs e)
{
var ui = new CameraCaptureUI();
ui.PhotoSettings.CroppedAspectRatio = new Size(4, 3);
var file = await ui.CaptureFileAsync(CameraCaptureUIMode.Photo);
if (file != null)
{
// store the file
var myFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("myImg.jpg");
await file.MoveAndReplaceAsync(myFile);
// display the file
var bitmap = new BitmapImage();
bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
Photo.Source = bitmap;
}
}
private async void delete_click(object sender, RoutedEventArgs e)
{
StorageFile filed = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filed != null)
{
await filed.DeleteAsync();
}
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
if (filefound != null)
{
// do something here
}
}
i am having same problem in deleting file from local storage. there are many files stored in the local storage with different names so how to delete other files. in the above case you have hard coded the file name to delete.
StorageFile filefound = await ApplicationData.Current.LocalFolder.GetFileAsync("myImg.jpg");
instead of myImg.jpg user want to delte other file then how user will delete
/// <summary>
/// Delete the indicated application file
/// </summary>
/// <param name="strFilePathName">The file path name to delete</param>
/// <returns>True, if successful; else false</returns>
public async static Task<bool> DeleteAppFile(string strFilePathName)
{
try
{
StorageFile fDelete = null;
if (!strFilePathName.Equals(""))
{
fDelete = await ApplicationData.Current.LocalFolder.GetFileAsync(strFilePathName);
if (fDelete != null)
{
try
{
await fDelete.DeleteAsync();
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
return false;
}
return true;
}
}
else
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile", "File path name is empty.");
}
catch (Exception ex)
{
AFFECTS.App.ShowMessage(true, "Error", "DeleteAppFile {" + strFilePathName + "}", ex.Message);
}
return false;
}

Categories

Resources