How to Change the File Location Programmatically

How can I change the file location programmatically?

log4net can handle this for you. Any appender property of type string can be formatted, in this case, using the log4net.Util.PatternString option handler. PatternString even supports the SpecialFolder enum which enables the following elegant config:

<appender name="LogFileAppender" type="log4net.Appender.RollingFileAppender" >
<file type="log4net.Util.PatternString"
value="%envFolderPath{CommonApplicationData}\\test.txt" />
...
</appender>

Here's a unit test that proofs the pudding:

[Test]
public void Load()
{
XmlConfigurator.Configure();
var fileAppender = LogManager.GetRepository()
.GetAppenders().First(appender => appender is RollingFileAppender);

var expectedFile =
Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData),
"test.txt");

Assert.That(fileAppender,
Is.Not.Null & Has.Property("File").EqualTo(expectedFile));
}

The following test verifies that log4net actually writes to disk (which basically makes this an "integration" test, not a unit test, but we'll leave it at that for now):

[Test]
public void Log4net_WritesToDisk()
{
var expectedFile =
Path.Combine(
Environment.GetFolderPath(
Environment.SpecialFolder.CommonApplicationData),
"test.txt");

if (File.Exists(expectedFile))
File.Delete(expectedFile);

XmlConfigurator.Configure();

var log = LogManager.GetLogger(typeof (ConfigTest));
log.Info("Message from test");

LogManager.Shutdown();

Assert.That(File.ReadAllText(expectedFile),
Text.Contains("Message from test"));
}

NB: I strongly suggest using the compact property syntax demonstrated in the above sample. Removing all those "<property name=" makes your config that much more readable.

how to programmatically set local file path to file uploader of a web page

For automation purposes, it's possible to provide a file name with SendKeys. The trick is to use a timer event or Task.Delay for asynchronous execution to let the file dialog open first. Here is a working example in C#, it should not be a problem to convert it to VB.NET.



Related Topics



Leave a reply



Submit