StreamWriter object doesn't work at all - c#

This code works fine within SaveFileDialog
private void buttonSaveAs_Click(object sender, EventArgs e)
{
try
{
if (selectedFileInfo != null)
{
// Save File
SaveFileDialog saveFileDialog1 = new SaveFileDialog();
saveFileDialog1.InitialDirectory = explorerTree2.SelectedPath;
// set a default file name
saveFileDialog1.FileName = Path.GetFileNameWithoutExtension(selectedFileInfo.Name) + "-COPY" + selectedFileInfo.Extension;
// set filters - this can be done in properties as well
saveFileDialog1.Filter = "HTM files (*.htm)|*.htm|HTML files (*.html)|*.html|XML files (*.xml)|*.xml|Text files (*.txt)|*.txt|All files (*.*)|*.*";
#region Define filter index
if (selectedFileInfo.Extension.Equals(".htm")) // HTM files (*.htm)|*.htm
{
saveFileDialog1.FilterIndex = 1;
}
else // All files (*.*)|*.*
{
saveFileDialog1.FilterIndex = 5;
}
#endregion
if (saveFileDialog1.ShowDialog() == DialogResult.OK)
{
using (StreamWriter sw = new StreamWriter(saveFileDialog1.FileName))
{
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
And another does not. And there NO is any error as well. Any clue?
private void buttonSave_Click(object sender, EventArgs e)
{
try
{
if (selectedFileInfo != null)
{
using (FileStream fs = new FileStream(selectedFileInfo.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
StreamWriter sw = new StreamWriter(fs);
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
P.S. This option does not work as well
using (FileStream fs = new FileStream(selectedFileInfo.Name, FileMode.OpenOrCreate, FileAccess.ReadWrite))
{
using (StreamWriter sw = new StreamWriter(fs))
{
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}

I found correct solution
where scintilla1.Text is string you have to write
and selectedFileInfo is a FileInfo object. In your case scintilla1.Text might be like a string or RichTextBox or any other text editor control.
private void buttonSave_Click(object sender, EventArgs e)
{
if (selectedFileInfo != null)
{
FileStream stream = null;
try
{
stream = selectedFileInfo.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
using (StreamWriter sw = new StreamWriter(stream))
{
sw.AutoFlush = true;
sw.Write(scintilla1.Text);
sw.Flush();
sw.Close();
}
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
if (stream != null)
stream.Close();
}
}
}

Related

Is it better to cache BinaryFormatter or keep re-creating it?

Is the code below good practice, or is it better to cache BinaryFormatter in a field so it doesn't keep getting re-created?
private void SaveLocalData()
{
BinaryFormatter bf = new BinaryFormatter();
FileStream fs = null;
try
{
fs = File.Create(Constants.LOCAL_BINARY_DATA_PATH);
bf.Serialize(fs, this.localData);
}
catch(System.Exception e)
{
print("error saving: " + e.Message);
}
finally
{
if (fs != null)
{
fs.Close();
}
}
}
when you accessing file system make sure you use using statements to avoid any memory leaks
don't see any problem recreating the formatter object
private void SaveLocalData()
{
var bf = new BinaryFormatter();
try
{
using (var fs = File.Create(Constants.LOCAL_BINARY_DATA_PATH))
{
bf.Serialize(fs, this.localData);
}
}
catch (System.Exception e)
{
print("error saving: " + e.Message);
}
}

How can be setted Console.SetOut(TextWriter) with multi thread C#?

Assuming I have a multi thread ForEach I would like that every cycle have the Console.WriteLine() converted into a file, the example I have found for mono thread is something like:
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream("C:\\Users\\Public\\Documents/Redirect.txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(ostrm);
}
catch (Exception e)
{
Console.WriteLine("Cannot open Redirect.txt for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(writer);
Now for multi thread I have try something like:
IList<String> testCaseList = ExcelDataAccess.GetTestCases();
Parallel.ForEach(testCaseList, new ParallelOptions { MaxDegreeOfParallelism = 1 }, currentTestCase =>`
{
FileStream ostrm;
StreamWriter writer;
TextWriter oldOut = Console.Out;
try
{
ostrm = new FileStream("C:\\Users\\Public\\Documents/Redirect" + currentTestCase +".txt", FileMode.OpenOrCreate, FileAccess.Write);
writer = new StreamWriter(ostrm);
}
catch (Exception e)
{
Console.WriteLine("Cannot open Redirect.txt for writing");
Console.WriteLine(e.Message);
return;
}
Console.SetOut(writer);
Console.WriteLine("Running test: " + currentTestCase);
//Do some other stuff and some Console.WriteLine();
}
But in this way inside every file what is written is not what expected and multi thread looks not handled correctly. How to solve this?

file in use by another process ... while i can copy

I get a "file in use by another process exception" when creating a email and wants to add this file as attachment.
When i try to copy the same file to an other directory there is no problem. (state of the file is still the same)
does anybody knows whats happening here? and how i can solve this?
here is the code:
public Boolean AddAttachment(string filePath, string newName = "")
{
try
{
MimeData mime = _message.AddAttachment(filePath);
if (!string.IsNullOrEmpty(newName))
{
mime.FileName = newName;
}
return true;
}
catch (Exception err)
{
if (! AddAttachmentIfInUse(filePath, newName))
{
AddErrorInfo(err.Message, "AddAttachment", err.Source);
return false;
}
else
{
return true;
}
}
}
private Boolean AddAttachmentIfInUse(string filePath, string newName = "")
{
byte[] data;
string contentType = "";
string fileName = Path.GetFileName(filePath);
try
{
using (FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read, FileShare.Read))
{
data = new byte[stream.Length];
stream.Read(data, 0, (int)stream.Length);
}
// data = File.ReadAllBytes(filePath);
MimeData mime = new MimeFactory().CreateMimeData();
mime.Data = data;
mime.ContentType = ContentType.Parse(contentType);
if (!string.IsNullOrEmpty(newName))
{
mime.FileName = newName;
}
else{
mime.FileName = fileName;
}
return true;
}
catch (Exception err)
{
AddErrorInfo(err.Message, "AddAttachmentIfInUse", err.Source);
return false;
}
}
thanks
The 1st function gets the the error in _message.AddAttachment(..) ...
I had to change the 2nd function: do not use File.Open() but use FileStream() and now it's working well.
using (var fs = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)){
data = new byte[fs.Length];
fs.Read(data, 0, (int)fs.Length);
}

Unable to attach image after scanning

I am able to scan the image using wia. After scanning I am trying to attach that scanned image. Below is the code but I am getting following error message:
microsoft.csharp.runtimebinder.runtimebinderexception:cannot perform runtime binding on a null reference.
private async void Button_Click_3(object sender, RoutedEventArgs e)
{
lblLoading_Copy.Content = "Loading . . .";
//lblLoading.Refresh();
await Task.Delay(1000);
try
{
using (var ms = new MemoryStream())
{
var document = new iTextSharp.text.Document(iTextSharp.text.PageSize.A4, 0, 0, 0, 0);
iTextSharp.text.pdf.PdfWriter.GetInstance(document, ms).SetFullCompression();
document.Open();
foreach (System.Drawing.Image aa in obj)
{
MemoryStream msimage = new MemoryStream();
aa.Save(msimage, ImageFormat.Jpeg);
var image = iTextSharp.text.Image.GetInstance(msimage.ToArray());
image.ScaleToFit(document.PageSize.Width, document.PageSize.Height);
document.Add(image);
}
document.Close();
string Path = ConfigurationManager.AppSettings["uploadfolderpath"].ToString();//confige path
string filename = "C3kycDMS" + DateTime.Now.ToString("yyyyMMddHHmmss") + ".pdf";
//Save using drive name
//File.WriteAllBytes(Path + filename, ms.ToArray());
byte[] test = ms.ToArray();
Service1.Service objService = new Service1.Service();
string result = objService.SaveScanedDocument(test, filename, 0);
if (result == "")
{
MessageBox.Show("File Upload unsuccessfull", "Error!", MessageBoxButton.OKCancel);
lblLoading_Copy.Content = "";
}
else
{
// MessageBox.Show("File Upload successfull", "Success!", MessageBoxButton.OKCancel);
lblLoading_Copy.Content = "";
}
pic_scan.Source = null;
var hostScript = BrowserInteropHelper.HostScript;
hostScript.document.ResponseData(filename);
// return ms.ToArray();
}
}
catch (Exception ex)
{
//MessageBox.Show(ex.ToString(), "Error", MessageBoxButton.OKCancel);
lblLoading.Content = "";
}

Best way to implement a file access check in a loop

I'm trying to find a better way to check for file access in a loop.
Here's my code:
while (true)
{
try
{
using (FileStream Fs = new FileStream(fileName, FileMode.Open, FileAccess.Write))
using (StreamReader stream = new StreamReader(Fs))
{
break;
}
}
catch (FileNotFoundException)
{
break;
}
catch (ArgumentException)
{
break;
}
catch (IOException)
{
Thread.Sleep(1000);
}
}
Here's what I've tried so far, but it does not work has exprected:
FileIOPermission writePermission = new FileIOPermission(FileIOPermissionAccess.Write, fileName);
while (true)
{
try
{
writePermission.Demand();
break;
}
catch (SecurityException e)
{
Thread.Sleep(1000);
}
}
AND
while (true)
{
if (SecurityManager.IsGranted(writePermission))
break;
Thread.Sleep(1000);
}
I wrote this the other day.
public static void Retry(Action fileAction, int iteration)
{
try
{
fileAction.Invoke();
}
catch (IOException)
{
if (interation < MaxRetries)
{
System.Threading.Thread.Sleep(IterationThrottleMS);
Retry(fileAction, ++iteration);
}
else
{
throw;
}
}
}
You would have to declare MaxRetries and IterationThrottleMS yourself, or perhaps make them parameters.
EDIT I include an example. As I admit, this would be over engineering unless it were resused
//A little prep
const int IterationThrottleMS = 1000;
const int MaxRetries = 5;
public static void Retry(Action fileAction)
{
Retry(fileAction, 1)
}
...
// Your first example
try
{
Retry(() => {
using (FileStream Fs = new FileStream(
fileName,
FileMode.Open,
FileAccess.Write)
StreamReader stream = new StreamReader(Fs);
});
}
catch (FileNotFoundException) {/*Somthing Sensible*/}
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}
...
// Your second example
try
{
Retry(() => writePermission.Demand());
}
catch (FileNotFoundException) {/*Somthing Sensible*/}
catch (ArgumentException) {/*Somthing Sensible*/}
catch (IOException) {/*Somthing Sensible*/}

Categories