hi,
This is a small class I made that allows you to expand the variables in a string. Much like what the windows api call does, this also allows you to define your own variable name and data. This is still in testing mode so there maybe a few things I need to fix, if you have any suggestions please feel free to let me know.
Hope you find this code us full.
Class code. VarStrExpand.cs
csharp Code:
using System.Collections.Generic;
//Expand vraible class by Ben Jones, Ver Alpha 1.0
//Allows you to define your own variable names and data.
//Last-updated 19/01/15
namespace ExpEnv
{
class VarStrExpand
{
private struct TVARIABLES
{
public string sVarName;
public string sVarData;
};
private string m_src = null;
private string m_ret = null;
private List<TVARIABLES> _vars;
public VarStrExpand()
{
_vars = new List<TVARIABLES>();
}
public void VariableAdd(string sName, string sData)
{
//Add variable and data.
TVARIABLES T;
T.sVarName = sName.ToUpper();
T.sVarData = sData;
_vars.Add(T);
}
public string Source
{
get
{
return m_src;
}
set
{
m_src = value;
}
}
public override string ToString()
{
//Expland the variables in the source string.
ExpandVar(this.Source);
//Return result.
return m_ret;
}
public void Clear()
{
//This just free eveything up.
this.m_ret = null;
this.m_src = null;
this._vars.Clear();
}
private string _VarGet(string sCheckName)
{
int J = 0;
string sRet = "";
while (J < _vars.Count)
{
if (_vars[J].sVarName == sCheckName)
{
//Get variable data.
sRet = _vars[J].sVarData;
}
//INC counter.
J++;
}
return sRet;
}
private void ExpandVar(string source)
{
int I = 0;
string sVriable = "";
string sData = "";
bool in_var = false;
//Append null char to end., just makes sure out I index
//does not go out of range sure there is a better way
//but it seems to work for my purpose.
source += '\0';
for (I = 0; I < source.Length; I++)
{
if (source[I] == '%')
{
//Set wether in or out of variable string %var%
in_var = (!in_var);
//Move index along to skip %
I += 1;
}
if (in_var)
{
//Get variable name.
sVriable += source[I].ToString().ToUpper();
}
else
{
if (sVriable.Length != 0)
{
//Get variable data.
sData = _VarGet(sVriable);
//Check variable length.
if (sData.Length == 0)
{
//Reapend variable tags %var%
sData = "%" + sVriable + "%";
}
}
//if (I >= source.Length)
//{
// break;
//}
//Build string
m_ret += sData + source[I];
//Clear variable.
sVriable = "";
sData = "";
}
}
//return sBuffer;
}
}
}
Example
csharp Code:
//Example
VarStrExpand v = new VarStrExpand();
//Source to expland.
v.Source = "%drv%\\%Docs%\\%Folder1%\\%File%";
//Add custom variables and data.
v.VariableAdd("drv", "D:");
v.VariableAdd("docs", "Work\\microsoft");
v.VariableAdd("folder1", "docs");
v.VariableAdd("file", "copyright.txt");
//Show result.
MessageBox.Show(v.ToString());
//Clear up the class.
v.Clear();