Your problem, as the exception says, is in class initialization Constantes
.
Check that ConfigurationManager.AppSettings["CaixaTrashPath"]
exists.
If it does not exist, an exception will be made, which if left untreated, will be transformed into a TypeInitializationException
for runtime
. This is because the variable could not be initialized CaixaTash
.
If you have no way to guarantee that "Caixatrashpath" exists, a solution can go through defining an explicit static constructor and try to extract the value:
public static string CaixaTrash;
static Constantes()
{
try
{
CaixaTrash = ConfigurationManager.AppSettings["CaixaTrashPath"];
}
catch(Exception ex) // E boa ideia tentar apanhar um tipo de excepcao mais especifico.
{
CaixaTrash = string.Empty;
// ou
throw new Exception("CaixaTrashPath nao encontrado")
}
}
Note that defining a explicit static constructor will not affect other static fields you have. According to the C specification#:
If a static constructor (§10.12) exists in the class, initialization
static fields occur immediately before constructor invocation
static. Otherwise, the static fields initialize and run before the
first static field use of this class.
This further explains why the exception is only raised when using the Path.Combine
.
==Extra note==
Prefer to use static properties instead of static fields. This way ensures control over reading and writing. Reply in SOEN on the subject
Thank you Omni. Actually, there was another item(frequencia) in Appsettings that was not declared. Even without mentioning it, the error was raised when trying to use the 'Caixatrashpath' that existed.
– SantanaFire
@Santanafire as explained in the C#specification, if this other item was also a static field of Constants when used
CaixaTrash
for the first time, all static fields were initialized, hence the other field failed.– Omni