Reputation: 85765
I am using file helpers and I put on top of my class [DelimitedRecord("|")]
I want to check though if the value is a "|" if not then I want to throw an exception..
public void WriteResults<T>(IList<T> resultsToWrite, string path, string fileName) where T: class
{
var attr = (DelimitedRecordAttribute)Attribute.GetCustomAttribute(typeof(T), typeof(DelimitedRecordAttribute));
if (attr.HasValue("|")) // has value does not exist.
{
FileHelperEngine<T> engine = new FileHelperEngine<T>();
engine.HeaderText = String.Join("|", typeof(T).GetFields().Select(x => x.Name));
string fullPath = String.Format(@"{0}\{1}-{2}.csv", path, fileName, DateTime.Now.ToString("yyyy-MM-dd"));
engine.WriteFile(fullPath, resultsToWrite);
}
}
What can I use to check for that attribute is on the class with that value?
Edit
This is what I see as available properties
Upvotes: 0
Views: 287
Reputation: 150108
You can retrieve an instance of DelimitedRecordAttribute
like this:
// t is an instance of the class decorated with your DelimitedRecordAttribute
DelimitedRecordAttribute myAttribute =
(DelimitedRecordAttribute)
Attribute.GetCustomAttribute(t, typeof (DelimitedRecordAttribute));
If DelimitedRecordAttribute
exposes a means of getting at the parameter (which it should), you can access the value via that means (typically a property), e.g. something like:
var delimiter = myAttribute.Delimiter
http://msdn.microsoft.com/en-us/library/71s1zwct.aspx
UPDATE
Since there doesn't seem to be a public property in your case, you can use reflection to enumerate the non-public fields and see if you can locate a field that holds the value, e.g. something like
FieldInfo[] fields = myType.GetFields(
BindingFlags.NonPublic |
BindingFlags.Instance);
foreach (FieldInfo fi in fields)
{
// Check if fi.GetValue() returns the value you are looking for
}
UPDATE 2
If this attribute is from filehelpers.sourceforge.net, the field you are after is
internal string Separator;
The full source code for that class is
[AttributeUsage(AttributeTargets.Class)]
public sealed class DelimitedRecordAttribute : TypedRecordAttribute
{
internal string Separator;
/// <summary>Indicates that this class represents a delimited record. </summary>
/// <param name="delimiter">The separator string used to split the fields of the record.</param>
public DelimitedRecordAttribute(string delimiter)
{
if (Separator != String.Empty)
this.Separator = delimiter;
else
throw new ArgumentException("sep debe ser <> \"\"");
}
}
UPDATE 3
Get the Separator field like this:
FieldInfo sepField = myTypeA.GetField("Separator",
BindingFlags.NonPublic | BindingFlags.Instance);
string separator = (string)sepField.GetValue();
Upvotes: 3