I have matlab script textcreator.m that create some result file output.txt.
And there is some matlab.aplication() reference that "translate" matlab function to c# and some of the code is hard to convert to c# and i decide just run the script i made.
using System;
using System.Collections.Generic;
using System.Text;
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute(#"cd d:\textcreator.m");
How to run matlab script textcreator.m when i click a button on my pc that have Matlab?
You have almost got it, but instead of matlab.Execute("cd d:\textcreator.m"), you should matlab.Execute("cd d:\"), then matlab.Execute("run textcreator.m"). So your code should be:
MLApp.MLApp matlab = new MLApp.MLApp();
matlab.Execute("cd d:\");
matlab.Execute("run textcreator.m");
I have also dug out a simple MLApp wrapper I wrote quite some time ago. Thought it would be useful for you.
class MLWrapper
{
private readonly MLApp.MLApp _mlapp;
public MLWrapper(bool visible = false)
{
_mlapp = new MLApp.MLApp();
if (visible)
ShowConsole();
else
HideConsole();
}
~MLWrapper()
{
Run("close all");
_mlapp.Quit();
}
public void ShowConsole()
{
_mlapp.Visible = 1;
}
public void HideConsole()
{
_mlapp.Visible = 0;
}
/// <summary>
/// Run a MATLAB command.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string Run(string cmd)
{
return _mlapp.Execute(cmd);
}
/// <summary>
/// Run a MATLAB script.
/// </summary>
/// <returns>Text output displayed in MATLAB console.</returns>
public string RunScript(string scriptName)
{
return Run($"run '{scriptName}'");
}
/// <summary>
/// Change MATLAB's current working folder to the specified directory.
/// </summary>
public void CD(string directory)
{
Run($"cd '{directory}'");
}
public object GetVariable(string varName)
{
_mlapp.GetWorkspaceData(varName, "base", out var data);
return data;
}
public void SetVariable(string varName, object value)
{
_mlapp.PutWorkspaceData(varName, "base", value);
}
}
Related
I have created an object which is used to control a piece of test equipment (oscilloscope) which communicates using the Visa library. This object (scope object) works fine, but there is one method I created to query the scope for a waveform average, which takes a while to execute (around a second or so), and blocks execution of the UI while it is acquiring the data.
To get around this problem, I initially tried creating a task object and using this task object to execute the function that is querying the scope for the data; but I found that something in the Visa driver object itself was apparently still executing on the main thread (and thus slowing down my UI).
I then did one more test and created a new thread, and had this thread call a function. Inside this function, I initialized the scope object, setup the operating parameters, and then called the long-running function. This time, my UI was as responive as normal with no slowdowns.
So now, It seems that I need to actually initialize the scope object inside a new thread in order to get it to truly run asynchronously. But now I have a new challenge. I need to access the objects properties and methods from the main thread to set things up, query status info, etc. Is there a clean way to effectively read and write to a class's properties and methods from another thread? Or are there any existing libraries available to make this simpler?
My current idea is to create a wrapper class for the scope object and then have this wrapper class initialize the scope object in a new thread. But I'm not sure of the best way to access the object's members efficiently. Or better yet, is there a better approach to this problem?
EDIT: Below is some more information and code for the test program I wrote. The UI is a just a simple form with Acquire and Connect buttons, and two labels (one for showing the measurements and the other shows a number that gets incremented as I click on the "Click" button:
Here's the code for the Scope Object I created:
using System;
using Ivi.Scope.Interop;
using Tektronix.Tkdpo2k3k4k.Interop;
using System.Diagnostics;
namespace Test_App
{
public class DPO4034
{
#region [NOTES] Installing TekVisa Drivers for DPO4034
/*
1. Download and install the TekVisa Connectivity Software from here:
https://www.tek.com/oscilloscope/tds7054-software/tekvisa-connectivity-software-v411
2. Check under Start -> All Programs -> TekVisa and see if the "Open Choice Installation Manager" shortcut works.If not, then update all shortcuts to point to the correct base folder for the TekVISA files, which is "C:\Program Files\IVI Foundation\VISA\".
3. Download the DPO4000 series IVI driver from here:
https://www.tek.com/oscilloscope/dpo4054-software/dpo2000-dpo3000-dpo4000-ivi-driver
4. After running the unzip utility, open the unzipped folder and goto x64 -> Shared Components, and run the IviCleanupUtility_2.0.0.exe utility to make sure no shared IVI components exist.
5. Run the IviSharedComponents64_2.1.1.exe file to install shared components.
6. Go up one folder and open the IVI Driver Folder and run the Tkdpo2k3k4k-x64.msi installer to install the scope IVI driver.
7. In the VS project, add references to the following COM components:
• IviDriverLib
• IviScopeLib
• Tkdpo2k3k4kLib
8. Right Click on each of the three references in the Solution Explorer and select Properties in the menu. When the properties window appears, set the "Embed Interop Types" property to False.
*/
#endregion
#region Class Variables
Tkdpo2k3k4kClass driver; // IVI Driver representing the DPO4034
IIviScope scope; // IVI Scope object representing the DPO4034
#endregion
#region Class Constructors
public DPO4034()
{
this.driver = new Tkdpo2k3k4kClass();
this.scope = (IIviScope)driver;
}
~DPO4034()
{
this.Disconnect();
}
#endregion
#region Public Properties
/// <summary>
/// Returns true if the scope is connected (initialized)
/// </summary>
public bool Connected
{
get
{
return this.driver.IIviDriver_Initialized;
}
}
#endregion
#region Public Methods
/// <summary>
/// Initializes the connection to the scope
/// <paramref name="reset"/>Resets the scope after connecting if set to true</param>
/// </summary>
/// <returns>True if the function succeeds</returns>
public bool Connect(bool reset = false)
{
try
{
if (!this.Connected)
{
this.Disconnect();
}
this.driver.Initialize("TCPIP::10.10.0.200::INSTR", true, reset, "Simulate=false, DriverSetup= Model=DPO4034");
return true;
}
catch (Exception ex)
{
PrintError(ex, "Connect");
return false;
}
}
/// <summary>
/// Closes the connection to the scope
/// </summary>
/// <returns>True if the function succeeds</returns>
public bool Disconnect()
{
try
{
if (this.Connected)
{
this.driver.Close();
}
return true;
}
catch (Exception ex)
{
PrintError(ex, "Disconnect");
return false;
}
}
/// <summary>
/// Reads the average value of the waveform on the selected channel
/// </summary>
/// <param name="channel">1-4 for channels 1 to 4</param>
/// <returns>The measured average value</returns>
public double ReadWaveformAverage(int channel)
{
if (this.Connected)
{
try
{
double value = 0;
this.scope.Measurements.Item["CH" + channel.ToString()].FetchWaveformMeasurement(IviScopeMeasurementEnum.IviScopeMeasurementVoltageAverage, ref value);
return value;
}
catch (Exception ex)
{
PrintError(ex, "ReadWaveformAverage");
return 0;
}
}
else
{
PrintError("Oscilloscope not connected", "ReadWaveformAverage");
return 0;
}
}
#endregion
#region Private Methods
/// <summary>
/// Prints an error message to the debug console
/// </summary>
/// <param name="err">Error object</param>
/// <param name="source">Source of the error</param>
private void PrintError(Exception err, string source = "") //, bool showMessageBox = false)
{
Debug.Print($"Error: {err.Message}");
Debug.Print($"Source: {source}");
}
/// <summary>
/// Prints an error message to the debug console
/// </summary>
/// <param name="err">Error object</param>
/// <param name="source">Source of the error</param>
private void PrintError(string error, string source = "")
{
Debug.Print($"Error: {error}");
Debug.Print($"Source: {source}");
}
#endregion
}
}
Here's the code for the version of the form that uses an async function and tasks to directly call the acquisition functions:
using System;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace Test_App
{
public partial class Form1 : Form
{
byte number = 0;
public Form1()
{
InitializeComponent();
}
private void cmdAcquire_Click(object sender, EventArgs e)
{
takeMeasurements();
}
async void takeMeasurements()
{
try
{
// Create new instance of the scope object and connect to it
DPO4034 Scope = new DPO4034();
Scope.Connect();
// Update status
PrintStatus(Scope.Connected ? "Connected" : "Error");
// Loop continuously and print the samples to the status label
while (Scope.Connected)
{
double inputVoltage = await Task.Run(() => Scope.ReadWaveformAverage(1));
double inputCurrent = await Task.Run(() => Scope.ReadWaveformAverage(2));
double outputVoltage = await Task.Run(() => Scope.ReadWaveformAverage(3));
PrintStatus($"CH1: {inputVoltage}\n" +
$"CH2: {inputCurrent}\n" +
$"CH3: {outputVoltage}\n");
}
}
catch (Exception)
{
PrintStatus("Error");
}
}
private void cmdIncrement(object sender, EventArgs e)
{
// This is just something for me to make the interface do to see
// how responsive it is
lblNumber.Text = number.ToString();
number++;
}
// Prints status text to the label on the form
private void PrintStatus(string text)
{
Status.Text = text;
}
}
}
and here's the code for the version of the form that uses a separate thread to run the scope object:
using System;
using System.Threading;
using System.Windows.Forms;
namespace Test_App
{
public partial class Form1 : Form
{
Thread t;
byte number = 0;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
t = new Thread(new ThreadStart(takeMeasurements));
}
private void cmdAcquire_Click(object sender, EventArgs e)
{
t.Start();
}
// Function to create scope object and take acquisitions
void takeMeasurements()
{
try
{
// Create new instance of the scope object and connect to it
DPO4034 Scope = new DPO4034();
Scope.Connect();
// Update status
PrintStatus(Scope.Connected ? "Connected" : "Error");
// Loop continuously and print the samples to the status label
while (Scope.Connected)
{
double inputVoltage = Scope.ReadWaveformAverage(1);
double inputCurrent = Scope.ReadWaveformAverage(2);
double outputVoltage = Scope.ReadWaveformAverage(3);
PrintStatus($"CH1: {inputVoltage}\n" +
$"CH2: {inputCurrent}\n" +
$"CH3: {outputVoltage}\n");
}
}
catch (Exception)
{
PrintStatus("Error");
}
}
private void cmdIncrement(object sender, EventArgs e)
{
// This is just something for me to make the interface do to see
// how responsive it is
lblNumber.Text = number.ToString();
number++;
}
// Prints status text to the label on the form
private void PrintStatus(string text)
{
if (!this.IsDisposed)
{
this.BeginInvoke((MethodInvoker)delegate
{
Status.Text = text;
});
}
else
{
t.Abort();
}
}
}
}
I hope this gives some more insight into what I'm trying to accomplish. Thank you all for your comments and I look forward to your feedback.
EDIT2: Just to be more clear, the method I would prefer to use (if possible) is the one using tasks. In the current program, the Scope object is initialized at the top of the form on the main thread and accessed by multiple objects within the program.
For anyone interested, I finally found a solution to the problem I was having with the GUI freezing when executing the ReadWaveformData() function.
The answer was to create a new thread inside of the Scope class that would call an Initialization function to initialize the internal scope and driver objects. Then the thread would do nothing but sit and host the instances until the ReadWavveformData() function is called inside a task. Here's the modified DPO4034 class:
using System;
using Ivi.Scope.Interop;
using Tektronix.Tkdpo2k3k4k.Interop;
using System.Diagnostics;
using System.Threading;
namespace Test_App
{
public class DPO4034
{
#region [NOTES] Installing TekVisa Drivers for DPO4034
/*
1. Download and install the TekVisa Connectivity Software from here:
https://www.tek.com/oscilloscope/tds7054-software/tekvisa-connectivity-software-v411
2. Check under Start -> All Programs -> TekVisa and see if the "Open Choice Installation Manager" shortcut works.If not, then update all shortcuts to point to the correct base folder for the TekVISA files, which is "C:\Program Files\IVI Foundation\VISA\".
3. Download the DPO4000 series IVI driver from here:
https://www.tek.com/oscilloscope/dpo4054-software/dpo2000-dpo3000-dpo4000-ivi-driver
4. After running the unzip utility, open the unzipped folder and goto x64 -> Shared Components, and run the IviCleanupUtility_2.0.0.exe utility to make sure no shared IVI components exist.
5. Run the IviSharedComponents64_2.1.1.exe file to install shared components.
6. Go up one folder and open the IVI Driver Folder and run the Tkdpo2k3k4k-x64.msi installer to install the scope IVI driver.
7. In the VS project, add references to the following COM components:
• IviDriverLib
• IviScopeLib
• Tkdpo2k3k4kLib
8. Right Click on each of the three references in the Solution Explorer and select Properties in the menu. When the properties window appears, set the "Embed Interop Types" property to False.
*/
#endregion
#region Class Variables
Tkdpo2k3k4kClass driver; // IVI Driver representing the DPO4034
IIviScope scope; // IVI Scope object representing the DPO4034
Thread t; // Thread to initialize the scope objects in to ensure that they async method calls do not run on the main thread
#endregion
#region Class Constructors
public DPO4034()
{
t = new Thread(new ThreadStart(Initialize));
t.Start();
// Wait for scope object to be initialized in the thread
while (this.scope == null);
}
~DPO4034()
{
this.Disconnect();
t.Abort();
}
#endregion
#region Public Properties
/// <summary>
/// Returns true if the scope is connected (initialized)
/// </summary>
public bool Connected
{
get
{
return this.driver.IIviDriver_Initialized;
}
}
#endregion
#region Public Methods
/// <summary>
/// Initializes the connection to the scope
/// <paramref name="reset"/>Resets the scope after connecting if set to true</param>
/// </summary>
/// <returns>True if the function succeeds</returns>
public bool Connect(bool reset = false)
{
try
{
if (!this.Connected)
{
this.Disconnect();
}
this.driver.Initialize("TCPIP::10.10.0.200::INSTR", true, reset, "Simulate=false, DriverSetup= Model=DPO4034");
return true;
}
catch (Exception ex)
{
PrintError(ex, "Connect");
return false;
}
}
/// <summary>
/// Closes the connection to the scope
/// </summary>
/// <returns>True if the function succeeds</returns>
public bool Disconnect()
{
try
{
if (this.Connected)
{
this.driver.Close();
}
return true;
}
catch (Exception ex)
{
PrintError(ex, "Disconnect");
return false;
}
}
/// <summary>
/// Reads the average value of the waveform on the selected channel
/// </summary>
/// <param name="channel">1-4 for channels 1 to 4</param>
/// <returns>The measured average value</returns>
public double ReadWaveformAverage(int channel)
{
if (this.Connected)
{
try
{
double value = 0;
this.scope.Measurements.Item["CH" + channel.ToString()].FetchWaveformMeasurement(IviScopeMeasurementEnum.IviScopeMeasurementVoltageAverage, ref value);
return value;
}
catch (Exception ex)
{
PrintError(ex, "ReadWaveformAverage");
return 0;
}
}
else
{
PrintError("Oscilloscope not connected", "ReadWaveformAverage");
return 0;
}
}
#endregion
#region Private Methods
private void Initialize()
{
this.driver = new Tkdpo2k3k4kClass();
this.scope = (IIviScope)driver;
// Does nothing but allow the objects to exist on the separate thread
while (true)
{
Thread.Sleep(int.MaxValue);
}
}
/// <summary>
/// Prints an error message to the debug console
/// </summary>
/// <param name="err">Error object</param>
/// <param name="source">Source of the error</param>
private void PrintError(Exception err, string source = "") //, bool showMessageBox = false)
{
Debug.Print($"Error: {err.Message}");
Debug.Print($"Source: {source}");
}
/// <summary>
/// Prints an error message to the debug console
/// </summary>
/// <param name="err">Error object</param>
/// <param name="source">Source of the error</param>
private void PrintError(string error, string source = "")
{
Debug.Print($"Error: {error}");
Debug.Print($"Source: {source}");
}
#endregion
}
}
If this is paired up with the version of the TestApp that uses the async tasks to execute the ReadWaveformData() function, then things run smoothly and I don't need to completely rewrite the scope class to get it to work in my program. Hope this is helpful for anyone else who may run into a similar challenge.
I am trying to open a sample project in the farseer with monogame in vs2017 but all the time I get this error:
internal static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
///
private static void Main(string[] args)
{
using (FarseerPhysicsGame game = new FarseerPhysicsGame())
{
game.Run();
}
}
}
Server start up error when trying to add a purger timer ( game feature) seems that the server is not allowed access?
PurgeTimer:
using System;
using System.Threading;
using System.Collections.Concurrent;
using Plus.HabboHotel.GameClients;
using Plus.HabboHotel.Rooms;
namespace Plus.HabboHotel.Minigames.Purge
{
/// <summary>
/// This will do a countdown before the match starts
/// </summary>
public class PurgeTimer
{
/// <summary>
/// Timer for our operation
/// </summary>
private Timer Timer;
public bool On = false;
/// <summary>
/// Constructor
/// </summary>
public PurgeTimer()
{
// Method to call when completed
TimerCallback TimerCallback = Ticked;
// Create a new instance of timer
Timer = new Timer(TimerCallback, null, 30000, Timeout.Infinite);
}
/// <summary>
/// Method is call when timer is finished
/// </summary>
/// <param name="info">The information</param>
public void Ticked(object info)
{
try
{
if (PurgeManager.Running)
{
foreach (GameClient client in PlusEnvironment.GetGame().GetClientManager()._clients.Values)
{
try
{
if (client == null)
{
continue;
}
client.SendWhisper("[Automatic Event Alert]: The hotel is currently under Purge Mode. All crime is legal.");
}
catch (Exception e)
{
}
}
Timer.Change(30000, Timeout.Infinite);
}
else
{
return;
}
}
catch { }
}
}
}
PurgeManager:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Plus.HabboHotel.Minigames.Purge;
using System.Threading.Tasks;
namespace Plus.HabboHotel.Minigames.Purge
{
public class PurgeManager
{
public static PurgeTimer MainTimer;
public static bool Running;
}
}
Error:
http://prntscr.com/9ss0qb I don't get while it's not accessible!
Firstly, please post the error directly into the question, not as a linked image.
The error Plus.HabboHotel.GameClients.GameClientManager._clients is inaccessible due to its protection level seems pretty clear. From the naming convention used I'd take a guess that the _clients collection is private.
Here is your problem.
From your GameClientManager class, you're trying to access a private field.
private ConcurrentDictionary<int, GameClient> _clients;
For more details regarding your problem, review this. What are Access Modifiers in C#?
Trying to unit test some simple code for a class project, however every time I try to run the test I get an error that there is no home.exe and no main static main method. However, we haven't gotten to the point where we are supposed to have either of those things yet, so how can I run the test without them?
My code
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Home
{
class InventoryType
{
/// <summary>
/// Selects the inventory type and returns the selected value
/// </summary>
public class InventorySelect
{
private string inventoryTypes;
public String InventoryTypes
{
set
{
inventoryTypes = value;
}
get
{
return inventoryTypes;
}
}
/// <summary>
/// Validate that the inventory is returning some sort of value
/// </summary>
/// <returns></returns>
public bool Validate()
{
if (InventoryTypes == null) return false;
return true;
}
}
}
}
My Test Code
using System;
using System.Text;
using System.Collections.Generic;
using System.Linq;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Home.InventoryType.InventorySelect;
namespace HomeTest
{
[TestClass]
public class TestInventoryTypeCase
{
[TestMethod]
public void TestInventoryTypeClass()
{
InventorySelect select = new InventorySelect();
select.inventoryTypes = "Collection";
if (Validate() = true)
Console.WriteLine("Test Passed");
else
if (Validate() = false)
Console.WriteLine("Test Returned False");
else
Console.WriteLine("Test Failed To Run");
Console.ReadLine();
}
}
}
OK, a couple things here.
Make sure that your Output type for your main project (the project to be tested) is ClassLibrary
Use Assertions in your tests
I created a ClassLibrary solution called ExampleLibrary. Created a class called InventoryType and copied in your code e.g.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ExampleLibrary
{
class InventoryType
{
/// <summary>
/// Selects the inventory type and returns the selected value
/// </summary>
public class InventorySelect
{
private string inventoryTypes;
public String InventoryTypes
{
set
{
inventoryTypes = value;
}
get
{
return inventoryTypes;
}
}
/// <summary>
/// Validate that the inventory is returning some sort of value
/// </summary>
/// <returns></returns>
public bool Validate()
{
if (InventoryTypes == null) return false;
return true;
}
}
}
}
I then created a Unit Test and coded it as follows:
using Microsoft.VisualStudio.TestTools.UnitTesting;
using ExampleLibrary;
namespace HomeTest
{
[TestClass]
public class TestInventoryTypeCase
{
[TestMethod]
public void TestInventoryTypeClass()
{
InventoryType.InventorySelect select = new InventoryType.InventorySelect();
select.InventoryTypes = "Collection";
Assert.IsTrue(select.Validate());
select.InventoryTypes = null;
Assert.IsFalse(select.Validate());
}
}
}
I compile and run the test as described above and it runs and returns Test Passed.
To run a test on the main menu bar at the top of your Visual Studio...
Test - Windows - Test Explorer
In the Test Explorer window, select the test you wish to run and click on the run Icon at the top of the window.
A bit of background:
I am currently working on an application that allows novice computer users to test their ping without having to go into the command prompt.
My application works, but I would very much like to take the application to the next level and feed in default form values from a locally stored .INI file.
I can give people the existing code, but I stress that this application works - I am just interested in advancing the code so I can read in default form values.
using System;
using System.Collections.Generic;
using System.Net;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.NetworkInformation;
namespace Ping_Application
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void pingButton_Click(object sender, EventArgs e)
{
if (pingAddressTextBox.Text != "")
{
DataTable resultsList = new DataTable();
resultsList.Columns.Add("Time", typeof(int));
resultsList.Columns.Add("Status", typeof(string));
for (int indexVariable = 1; indexVariable <= timesToPing.Value; indexVariable++)
{
string stat = "";
Ping pinger = new Ping();
PingReply reply = pinger.Send(pingAddressTextBox.Text);
if (reply.Status.ToString() != "Success")
stat = "Failed";
else
stat = reply.RoundtripTime.ToString();
pinger.Dispose();
resultsList.Rows.Add(Convert.ToInt32(reply.RoundtripTime), reply.Status.ToString());
}
resultsGrid.DataSource = resultsList;
minPing.Text = resultsList.Compute("MIN(time)", "").ToString();
maxPing.Text = resultsList.Compute("MAX(time)", "").ToString();
avgPing.Text = resultsList.Compute("AVG(time)", "").ToString();
}
else
{
MessageBox.Show("You are required to enter an address.");
}
}
private void Form1_Load(object sender, EventArgs e)
{
}
}
}
I am uncertain how to go about it? Where would the default.ini file be stored for my application?
Also any comments on the existing code are welcomed.
If anyone can help I would be grateful.
Many Thanks,
J
You can store your default values in ini file (i.e config file), this default file will be stored in your system D or C folder...
and from that file you can get those default values from the ini file by the following method
/// <summary>
/// This will read config.ini file and return the specific value
/// </summary>
/// <param name="MainSection">Main catergory name</param>
/// <param name="key">name of the key in main catergory</param>
/// <param name="defaultValue">if key is not in the section, then default value</param>
/// <returns></returns>
public static string getIniValue(string MainSection, string key, string defaultValue)
{
IniFile inif = new IniFile(AppDataPath() + #"\config.ini");
string value = "";
value = (inif.IniReadValue(MainSection, key, defaultValue));
return value;
}
public static string AppDataPath()
{
gCommonAppDataPath = #"c:\" + gCompanyName + #"\" + gProductName; // your config file location path
return gCommonAppDataPath;
}
make a class like this INifile.cs and place the below code in ini.cs
public class IniFile
{
public string path;
[DllImport("kernel32")]
private static extern long WritePrivateProfileString(string section,string key,string val,string filePath);
[DllImport("kernel32")]
private static extern int GetPrivateProfileString(string section,string key,string def,StringBuilder retVal,int size,string filePath);
/// <summary>
/// INIFile Constructor.
/// </summary>
/// <param name="INIPath"></param>
public IniFile(string INIPath)
{
path = INIPath;
}
/// <summary>
/// Write Data to the INI File
/// </summary>
/// <param name="Section"></param>
/// Section name
/// <param name="Key"></param>
/// Key Name
/// <param name="Value"></param>
/// Value Name
public void IniWriteValue(string Section,string Key,string Value)
{
WritePrivateProfileString(Section,Key,Value,this.path);
}
/// <summary>
/// Read Data Value From the Ini File
/// </summary>
/// <param name="Section"></param>
/// <param name="Key"></param>
/// <param name="Path"></param>
/// <returns></returns>
public string IniReadValue(string Section,string Key,string Default)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section,Key,Default,temp,255,this.path);
return temp.ToString();
}
public void IniWriteString(string Section, string Key, string Value)
{
WritePrivateProfileString(Section, Key, Value, this.path);
}
public string IniReadString(string Section, string Key, string Default)
{
StringBuilder temp = new StringBuilder(255);
int i = GetPrivateProfileString(Section, Key, Default, temp, 255, this.path);
return temp.ToString();
}
}
and the values in config file look like this ....
[System]
GroupCode=xx
SiteCode=1234
MemberPrefix=xxx
AutoStart=no
EnablePosButton=yes....
you can get this values like by using
string a = getIniValue("System", "Sitecode", "");
you will get the value like this 1234
pls let me know if this is unclear to understand
i hope it will helps you......
If you are using Visual Studio 2005/2008 or 2010, using INI might not be a good choice. Instead you can use the off-the-shelf tools provided by Visual Studio, by clicking:
Project> Properties > Settings Tab
where you can add user settings and bind it to your GUI form. Visual Studio takes care of most of the stuff for you, and when you want to reference that variable, use the below syntax:
string LocalString=Properties.Settings.Default.YourSettings;
Moreover, a single call helps to save all the staff to archives.
Properties.Settings.Default.Save();
For even more details, please refer to the book Windows Form 2.0 Data Binding.