XML being overwirtten then program is re-opened - c#

so here it is my code.
public List<Serialization> list = null;
private void UCAPIn_Load(object sender, EventArgs e)
{
list = new List<Serialization>();
if (File.Exists("date.XML"))
{
var doc = XDocument.Load("data.XML");
foreach (XElement element in doc.Descendants("Serialization"))
{
list.Add(new Serialization()
{ ID = element.Element("ID").Value,
APIKEY = element.Element("APIKEY").Value,
VCODE = element.Element("VCODE").Value });
}
}
}
public void button1_Click(object sender, EventArgs e)
{
{
try
{
Serialization info = new Serialization();
info.APIKEY = txtAPI.Text;
info.VCODE = txtVerC.Text;
info.ID = Guid.NewGuid().ToString();
list.Add(info);
Serialization.SaveData(list, "data.XML");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
private void button2_Click(object sender, EventArgs e)
{
this.Close();
}
private void whatIsThisToolStripMenuItem_Click(object sender, EventArgs e)
{
}
// end of UCAPIn
public class Serialization
{
private string id;
private string APIkey;
private string VCode;
public string ID
{
get { return id; }
set { id = value; }
}
public string APIKEY
{
get { return APIkey; }
set { APIkey = value; }
}
public string VCODE
{
get { return VCode; }
set { VCode = value; }
}
public static void SaveData(List<Serialization> list, string Filename)
{
File.Delete(Filename);
XmlSerializer sr = new XmlSerializer(list.GetType());
TextWriter writer = new StreamWriter(Filename, true);
sr.Serialize(writer, list);
writer.Close();
}
}
it create my XML and adds to it (multiple entries) but when i close the program and reopen it add some more data in the older data is gone, overwritten by the new.
Can anyone help me with this one?
(thanks in advance)
XML Sample (when File.Delete(Filename); is removed.:
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSerialization xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Serialization>
<ID>f2310827-93d0-42aa-9bfe-32624ee5f97b</ID>
<APIKEY>1234</APIKEY>
<VCODE>1234</VCODE>
</Serialization>
</ArrayOfSerialization>
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSerialization xmlns:xsi="http://www.w3.org/2001/XMLSchema- instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Serialization>
<ID>df354c83-1ae2-4cfc-b802-c9682f24f3f6</ID>
<APIKEY>123</APIKEY>
<VCODE>123</VCODE>
</Serialization>
</ArrayOfSerialization>
<?xml version="1.0" encoding="utf-8"?>
<ArrayOfSerialization xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Serialization>
<ID>df354c83-1ae2-4cfc-b802-c9682f24f3f6</ID>
<APIKEY>123</APIKEY>
<VCODE>123</VCODE>
</Serialization>
<Serialization>
<ID>a8f6737e-6c08-4e7a-b041-c16b502d4a60</ID>
<APIKEY>1234</APIKEY>
<VCODE>1234</VCODE>
</Serialization>
</ArrayOfSerialization>

Hope this sample code helps you.
I'm using the same property class that you are using "Serialization"
For Deserialization use this method:
public List<Serialization> XMLDeserialize()
{
XmlSerializer deserializer = new XmlSerializer(typeof(List<Serialization>));
TextReader reader = new StreamReader(xmlPath);
var XMLDeserialize = (List<Serialization>) deserializer.Deserialize(reader);
reader.Dispose();
return XMLDeserialize;
}
To update the xml file use this function:
public void UpdateXMLSerialize(List<Serialization> objXmlData)
{
XmlSerializer serializer = new XmlSerializer(typeof(List<Serialization>));
using (TextWriter writer = new StreamWriter(xmlPath))
{
serializer.Serialize(writer, objXmlData);
}
}
To add new data in xml on click event:
private void Add_Click(object sender, EventArgs e)
{
List<Serialization> list = new List<Serialization>();
if (File.Exists(xmlPath))
{
list = XMLDeserialize();
Serialization obj = new Serialization() { ID = "NewData", APIKEY = "NewAPIKey", VCODE = "NewVCode" };
list.Add(obj);
UpdateXMLSerialize(list);
}
}

Related

how to do a multithreaded text search using background worker and display the entire line in a listview in c#

So, I have a win form where I have to search for a string in a text file and display the line number and the entire line if I found the string. The search has to be multithreaded and all the line numbers and the lines must be on a listview. For example if the word "language" is in line number 60 , the listview must display:
60 "the line has the word language"
I have used the background worker in this regard but I am not being able to display the correct line number and the lines. Firstly, one line is being displayed multiple times and secondly, the line number is always coming to be 0. However, when I output the result in Console, the result is correct. I think I am making some error in putting the result into the listview.
Here' s my main form.cs
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// private bool start_cancel;
bool bln = true;
private void StartCancelbtn_Click(object sender, EventArgs e)
{
if (bln)
text2();
else
text1();
bln = !bln;
}
private void text1()
{
StartCancelbtn.Text = "Start";
this.backgroundWorker1.CancelAsync();
}
private void text2()
{
StartCancelbtn.Text = "Cancel";
StartThread();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
System.ComponentModel.BackgroundWorker worker;
worker = (System.ComponentModel.BackgroundWorker)sender;
// Get the Words object and call the main method.
main_work WC = (main_work)e.Argument;
WC.CountWords(worker, e);
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
}
private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
main_work.ReportState state =
(main_work.ReportState)e.UserState;
ListViewItem l1 = new ListViewItem();
l1.Text = state.LinesCounted.ToString();
l1.SubItems.Add(state.line);
listView1.Items.Add(l1);
}
private void backgroundWorker1_RunWorkerCompleted(object sender,
RunWorkerCompletedEventArgs e)
{
if (e.Error != null)
MessageBox.Show("Error: " + e.Error.Message);
else if (e.Cancelled)
MessageBox.Show("Word counting canceled.");
else
MessageBox.Show("Finished counting words.");
}
private void StartThread()
{
main_work WC = new main_work();
WC.CompareString = this.searchtext.Text;
WC.SourceFile = this.filenametextbox.Text;
// Start the asynchronous operation.
backgroundWorker1.RunWorkerAsync(WC);
}
private void browsebtn_Click(object sender, EventArgs e)
{
using (OpenFileDialog brw = new OpenFileDialog())
{
if (brw.ShowDialog() == DialogResult.OK)
{
using (StreamReader sr = new StreamReader(brw.FileName))
{
filenametextbox.Text = brw.FileName.ToString();
}
}
}
}
}
}
Here is my main_work class where the actual comparison is happening:
class main_work
{
public class ReportState
{
public int LinesCounted;
public string line;
}
Queue q = new Queue();
public string SourceFile;
public string CompareString;
public string line2 ;
public int linenumber=0;
public int linenumber1 = 0;
int LinesCounted1;
// public string line2;
public void CountWords(
System.ComponentModel.BackgroundWorker worker,
System.ComponentModel.DoWorkEventArgs e)
{
// Initialize the variables.
ReportState state = new ReportState();
string line1 = "";
int elapsedTime = 1;
DateTime lastReportDateTime = DateTime.Now;
if (CompareString == null ||
CompareString == System.String.Empty)
{
MessageBox.Show("Please Enter a string to be searched");
}
else
{
// Open a new stream.
using (System.IO.StreamReader myStream = new System.IO.StreamReader(SourceFile))
{
// Process lines while there are lines remaining in the file.
while (!myStream.EndOfStream)
{
if (worker.CancellationPending)
{
e.Cancel = true;
// break;
}
else
{
line1 = myStream.ReadLine();
line2 = (CountInString(line1, CompareString));
LinesCounted1 = (linenumbercount(line1, CompareString, linenumber1));
// Raise an event so the form can monitor progress.
int compare = DateTime.Compare(
DateTime.Now, lastReportDateTime.AddSeconds(elapsedTime));
if (compare > 0)
{
state.LinesCounted = LinesCounted1;
state.line = line2;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
System.Threading.Thread.Sleep(1);
}
}
// Report the final count values.
state.LinesCounted = LinesCounted1;
state.line = line1;
worker.ReportProgress(0, state);
lastReportDateTime = DateTime.Now;
}
}
}
private string CountInString(
string SourceString,
string CompareString)
{
if (SourceString.Contains(CompareString))
{
line2 = SourceString;
Console.WriteLine(SourceString);
}
return line2;
}
private int linenumbercount(
string SourceString,
string CompareString,
int linenumber)
{
// Lines = 0;
if (SourceString == null)
{
return 0;
}
if (SourceString.Contains(CompareString))
{
Console.WriteLine(linenumber);
}
linenumber++;
return linenumber;
}
}
Any feedback will be helpful. Please let me know what I am doing wrong and where is it that I am making a mistake as I am new to background worker and multithreading. Thanks.

Outlook 2016 VSTO Folder Add event fires only once

Am creating a outlook add-in to track mail processing from mailbox. Am wrapping the folders and the items(adding some events into it ) and storing them in a local list to avoid GC clearing all the events after first execution. However still the folder add event only fires once. Not sure what is the problem.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Xml.Linq;
using OutlookNS = Microsoft.Office.Interop.Outlook;
using Office = Microsoft.Office.Core;
using System.Net;
using System.Windows.Forms;
namespace OutlookAuditor
{
public partial class ThisAddIn
{
#region private variables
OutlookNS._NameSpace outNS;
OutlookNS.Explorer explorer;
string profileName = string.Empty;
List<SuperMailFolder> wrappedFolders = new List<SuperMailFolder>();
Logger logger = new Logger();
SuperMailFolder folderToWrap;
#endregion
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
try
{
OutlookNS.Application application = this.Application;
//Get the MAPI namespace
outNS = application.GetNamespace("MAPI");
//Get UserName
string profileName = outNS.CurrentUser.Name;
//Create a new outlook application
//I had to do this because my systems default mail box was ost file other just the below commented line is enough
//OutlookNS.MAPIFolder inbox = outNS.GetDefaultFolder(OutlookNS.OlDefaultFolders.olFolderInbox) as OutlookNS.MAPIFolder;
OutlookNS.MAPIFolder inbox;
OutlookNS.Folders folders = outNS.Folders;
OutlookNS.MAPIFolder selectedFolder = null;
if (folders.Count > 1)
{
List<string> folderNames = new List<string>();
foreach (OutlookNS.Folder folder in folders)
{
folderNames.Add(folder.Name);
}
using (selectMailBox frmSelect = new selectMailBox(folderNames))
{
if (DialogResult.OK == frmSelect.ShowDialog())
{
selectedFolder = folders[frmSelect.SelectedFolder];
}
}
}
else
{
selectedFolder = folders[1];
}
logger.SaveLog("Folder Selected " + selectedFolder.Name);
inbox = selectedFolder.Folders["Inbox"];//as OutlookNS.MAPIFolder;
//Create a super mail folder
folderToWrap = new SuperMailFolder(inbox, profileName);
wrappedFolders.Add(folderToWrap);
wrappedFolders.AddRange(folderToWrap.wrappedSubFolders);
//System.Runtime.InteropServices.Marshal.ReleaseComObject(inbox);
}
catch (Exception ex)
{
logger.WriteException(ex);
}
finally
{
}
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
#region SuperMailItem object
class SuperMailItem
{
//local variable for avoiding GC invocation
OutlookNS.MailItem item;
string _profileName;
OutlookAuditor.Common.AuditItem auditItem;
string parentMailID;
string _folderName = string.Empty;
OutlookNS.MailItem replyItem;
Logger logger = new Logger();
//constructor that wraps mail item with required events
internal SuperMailItem(OutlookNS.MailItem MailItemToWrap, string profileName,string folderName)
{
try
{
item = MailItemToWrap as OutlookNS.MailItem;
_folderName = folderName;
if (item is OutlookNS.MailItem)
{
logger.SaveLog(item.Subject);
item.PropertyChange += MailItemToWrap_PropertyChange;
//item.PropertyChange += new OutlookNS.ItemEvents_10_PropertyChangeEventHandler(MailItemToWrap_PropertyChange);
((OutlookNS.ItemEvents_10_Event)item).Reply += SuperMailItem_Reply;
}
}
catch(Exception ex)
{
logger.WriteException(ex,"SuperMailItem Constructor");
}
}
void SuperMailItem_Reply(object Response, ref bool Cancel)
{
try
{
parentMailID = string.Empty;
replyItem = Response as OutlookNS.MailItem;
((OutlookNS.ItemEvents_10_Event)replyItem).Send += SuperMailItem_Send;
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
//this event is not firing
void SuperMailItem_Send(ref bool Cancel)
{
try
{
if (!Cancel)
{
createAuditItem();
auditItem.ActionDescription = "REPLY_SENT";
SaveLog();
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
//property change event- fires when any property of a mail item changes
void MailItemToWrap_PropertyChange(string Name)
{
try
{
createAuditItem();
//We are interested in UnRead property, if this property changes audit.
if (Name == "UnRead")
{
if (!item.UnRead)
{
auditItem.ActionDescription = "MAIL_READ";
}
else
{
auditItem.ActionDescription = "MAIL_UNREAD";
}
}
SaveLog();
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
void createAuditItem()
{
auditItem = new Common.AuditItem();
auditItem.ActionTimestamp = DateTime.Now;
auditItem.EntryID = item.EntryID;
auditItem.ProfileName = _profileName;
auditItem.ReceivedTimestamp = item.ReceivedTime;
auditItem.SystemIP = Helper.SystemIP();
auditItem.UserName = Helper.UserID();
auditItem.OriginalMailSentBy = item.Sender.Name;
auditItem.FolderName = _folderName;
auditItem.Subject = item.Subject;
}
void SaveLog()
{
Logger logger = new Logger();
logger.Save(auditItem);
}
}
#endregion
#region SuperMailFolder object
class SuperMailFolder
{
#region private variables
OutlookNS.MAPIFolder _wrappedFolder;
string _profileName;
List<SuperMailItem> wrappedItems = new List<SuperMailItem>();
public List<SuperMailFolder> wrappedSubFolders = new List<SuperMailFolder>();
string folderName = string.Empty;
Logger logger = new Logger();
#endregion
#region constructor
internal SuperMailFolder(OutlookNS.MAPIFolder folder, string profileName)
{
try
{
//assign it to local private master
_wrappedFolder = folder;
folderName = folder.Name;
_profileName = profileName;
//assign event handlers for the folder
_wrappedFolder.Items.ItemAdd +=Items_ItemAdd;
_wrappedFolder.Items.ItemRemove += Items_ItemRemove;
refreshItemList();
//Go through all the subfolders and wrap them as well
foreach (OutlookNS.MAPIFolder tmpFolder in _wrappedFolder.Folders)
{
logger.SaveLog("Wrapping folder " + tmpFolder.Name);
SuperMailFolder tmpWrapFolder = new SuperMailFolder(tmpFolder, _profileName);
wrappedSubFolders.Add(tmpWrapFolder);
wrappedSubFolders.AddRange(tmpWrapFolder.wrappedSubFolders);
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
#endregion
void Items_ItemRemove()
{
refreshItemList();
}
#region Handler of addition item into a folder
void Items_ItemAdd(object Item)
{
try
{
if (Item is OutlookNS.MailItem)
{
OutlookNS.MailItem item = Item as OutlookNS.MailItem;
wrappedItems.Add(new SuperMailItem(item, _profileName, folderName));
logger.SaveLog("Adding new item. New collection count:" + wrappedItems.Count.ToString());
OutlookAuditor.Common.AuditItem auditItem = new Common.AuditItem();
auditItem.ActionTimestamp = DateTime.Now;
auditItem.EntryID = item.EntryID;
auditItem.ProfileName = _profileName;
auditItem.ReceivedTimestamp = item.ReceivedTime;
auditItem.SystemIP = Helper.SystemIP();
auditItem.UserName = Helper.UserID();
auditItem.ActionDescription = "FOLDER_ADD";
auditItem.FolderName = folderName;
auditItem.OriginalMailSentBy = item.Sender.Name;
auditItem.Subject = item.Subject;
logger.Save(auditItem);
}
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
void refreshItemList()
{
try
{
wrappedItems.Clear();
wrappedItems = new List<SuperMailItem>();
logger.SaveLog("Wrapping items in " + folderName);
//Go through all the items and wrap it.
foreach (OutlookNS.MailItem item in _wrappedFolder.Items)
{
try
{
if (item is OutlookNS.MailItem)
{
OutlookNS.MailItem mailItem = item as OutlookNS.MailItem;
SuperMailItem wrappedItem = new SuperMailItem(mailItem, _profileName, folderName);
wrappedItems.Add(wrappedItem);
}
}
catch (Exception ex)
{
logger.WriteException(ex);
}
}
logger.SaveLog("Wrapped items in " + folderName + ":" + wrappedItems.Count.ToString());
}
catch(Exception ex)
{
logger.WriteException(ex);
}
}
#endregion
}
#endregion
static class Helper
{
public static string SystemIP()
{
string hostName = Dns.GetHostName();
string hostAddress = Dns.GetHostByName(hostName).AddressList[0].ToString();
return hostAddress;
}
public static string UserID()
{
return System.Security.Principal.WindowsIdentity.GetCurrent().Name;
}
}
}
The following code is the problem:
_wrappedFolder.Items.ItemAdd +=Items_ItemAdd;
_wrappedFolder.Items.ItemRemove += Items_ItemRemove;
The object that fires the events must be alive - in your case you set up an event handler on an implicit variable returned from the _wrappedFolder.Items property - as soon as the GC releases that implicit variable, no events will fire. Declare the Items object on the class level to make sure it stays referenced and alive.

XmlSerializer.Serialize() fails to update XML file

So far I've followed the textbook route of adding adding data to an XML file; first, I created a class:
[Serializable]
public class Note
{
public string Notes { get; set; }
}
And then done this:
private void addButton_Click(object sender, RoutedEventArgs e)
{
string stringToAdd = textBox.Text;
Notes.Add(stringToAdd);
using (StringWriter myStringWirter = new StringWriter())
{
XmlSerializer myXML = new XmlSerializer(typeof(Note));
Note myNote = new Note();
myNote.Notes = stringToAdd;
myXML.Serialize(myStringWirter, myNote);
using (StreamWriter myStreamWriter = new StreamWriter("Notes.xml"))
{
myStreamWriter.Write(myStringWirter);
}
}
But Notes.xml doesn't get updated. Why?
Edit. Now it works. Just by using List instead of Note.

How to return an error from a class

I am new to c# and I don't know if I am doing this right. My problem is that I need to return the error from a class(.dll) but I don't know how.It only returns true or false. This is the code of my class:
namespace DigitalAssetConverter
{
public class ConvertImage
{
public Boolean ImagePath(string filePath)
{
try
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
return true;
}
}
catch
{
return false;
}
}
}
}
and I use it like this:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
if (ci.ImagePath(#"C:\tryConvert\LP_10078.eps"))
{
MessageBox.Show("Success!");
}
else
{
MessageBox.Show("Failed.");
}
}
Omit the try/catch block and make the return type void:
public void ImagePath(string filePath)
{
MagickReadSettings settings = new MagickReadSettings();
settings.ColorSpace = ColorSpace.RGB;
using (MagickImage image = new MagickImage(filePath))
{
image.Read(filePath, settings);
image.Resize(500, 500);
image.Write(Path.ChangeExtension(filePath, ".jpg"));
}
}
The exception (if any) will bubble up on its own, and you can place a try/catch block in the btnConvert_Click event to handle it instead:
private void btnConvert_Click(object sender, EventArgs e)
{
ConvertImage ci = new ConvertImage();
try
{
ci.ImagePath(#"C:\tryConvert\LP_10078.eps")
MessageBox.Show("Success!");
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}

OpenFileDialog filename serialization

In writing a program where I need to serialize an AppSettings object which consists of several properties including one that will be used to store a last used filename, I have found that the FileName property is placed into my object (by assignment) but it does not serialize to the xml file. No exceptions are thrown and no data is written.
But conversely, if I programmtically modify the object
tc.TheDataFile = "c:\\Documents And Settings\\SomeUser\\Sample\\a test file.txt";
instead of
tc.TheDataFile = theDialog.FileName;
That will work. Can someone please provide some insight with regard to what I am missing?
Here is a simple version of the program that is directly related to the problem.
The test class which will theoretically hold the AppSettings ---
[Serializable()]
public class TestClass
{
private string m_TheDataFile;
private bool m_UseLastKnownDataFile = true;
public bool UseLastKnownDataFile
{
get
{
return m_UseLastKnownDataFile;
}
set
{
m_UseLastKnownDataFile = value;
}
}
public string TheDataFile
{
get
{
return m_TheDataFile;
}
set
{
m_TheDataFile = value;
}
}
}
public class TestClassHelper
{
public static TestClass Load()
{
XmlSerializer serializer = new XmlSerializer(typeof(TestClass));
TestClass retVal;
TextReader reader = null;
bool fileNotFound = false; ;
try
{
reader = new StreamReader("TestClassConfig.xml");
}
catch (FileNotFoundException)
{
fileNotFound = true;
}
if (fileNotFound)
{
retVal = new TestClass();
}
else
{
retVal = (TestClass)serializer.Deserialize(reader);
reader.Close();
}
return retVal;
}
public static void Save(TestClass settings)
{
XmlSerializer serializer = new XmlSerializer(typeof(TestClass));
TextWriter writer = new StreamWriter("TestClassConfig.xml");
serializer.Serialize(writer, settings);
writer.Close();
}
}
And here is the form which will prompt the user for a filename. In this test, there is a form with one button.
public partial class Form1 : Form
{
TestClass tc = null;
public Form1()
{
InitializeComponent();
tc = TestClassHelper.Load();
}
private void button1_Click(object sender, EventArgs e)
{
OpenFileDialog theDialog = new OpenFileDialog();
string fileName = string.Empty;
theDialog.CheckFileExists = true;
theDialog.CheckPathExists = true;
theDialog.Multiselect = false;
theDialog.FileName = string.Empty;
if (theDialog.ShowDialog() == DialogResult.OK)
{
tc.TheDataFile = theDialog.FileName;
}
else
{
tc.TheDataFile = string.Empty;
}
}
private void Form1_FormClosed(object sender, FormClosedEventArgs e)
{
TestClassHelper.Save(tc);
}
}
Edit To Add:
I'm using Microsoft Visual Studio 2005 Team Edition w/Dot Net 2.0.50727 SP1, with no options to upgrade the development environment.
Solution
I'm not exactly sure why this happens, but the OpenFileDialog control must change the current operating directory of the program. When the object is deserialized to the xml file, it no longer writes where it originally opened. Rather it is created in the new directory.
I corrected the problem by making the XML read and write location more specific.
The problem is that you are setting tc.TheDataFile = fileName; after the if block, but you never assign anything to fileName except when you initialize it to string.Empty. One fix would be:
if (theDialog.ShowDialog() == DialogResult.OK)
{
fileName = theDialog.FileName;
}
// record last used data file
tc.TheDataFile = fileName;
or just
if (theDialog.ShowDialog() == DialogResult.OK)
{
tc.TheDataFile = theDialog.FileName;
}
Note that running your test in the debugger and "watch"ing the variables would have made the problem fairly easy to spot.

Categories

Resources