Is there a way to get the full filename from the Log Class?
The logger creates a file with a format like C:\MyPath\log-20160631.txt
I can not access the source filename which i used for the init of the logger.
Edit:
Here is the init of the logger:
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.WriteTo.LiterateConsole()
.WriteTo.RollingFile(#"C:\MyPath\log.txt")
.CreateLogger();
In every location in the code i can use e.g. Log.Information() but how i get the Sink information? I want to get the filename which i passed to rolling file sink.
My current workaround is to generate the real file manually (crazy ugly code):
public string LogFilename
{
get
{
string path = Path.GetDirectoryName(LogFilenameTemplate);
string filenameWithoutExtension = Path.GetFileNameWithoutExtension(LogFilenameTemplate);
string extension = Path.GetExtension(LogFilenameTemplate);
string date = DateTime.Now.ToString("yyyyMMdd");
string fullFilename = Path.Combine(path, filenameWithoutExtension + "-" + date + extension);
return fullFilename;
}
}
Format i got from GitHub Repo.
No, there's no way to retrieve the filename from Serilog. Your best available option is to use the System.IO classes to list files in the directory, and then open the one with the most recent modification date.
Related
Hi I have a code that you can save file and give specific file naming.
the problem is how can I check if file exist in the folder directory.
What I'm trying to do is like this.
FileInfo fileInfo = new FileInfo(oldPath);
if (fileInfo.Exists)
{
if (!Directory.Exists(newPath))
{
Directory.CreateDirectory(newPath);
}
fileInfo.MoveTo(string.Format("{0}{1}{2}", newPath, extBox1t.Text + "_" + textBox2.Text + "_" + textBox3.Text, fileInfo.Extension));
im trying to add MessageBox.Show in the below
if (!Directory.Exists(newPath))
{
MessageBox.Show("File Exist. Please Rename!");
Directory.CreateDirectory(newPath);
But it does not work. Or is there a way to add extension name at the last part of filename it should like this
Example: STACKOVERFLOWDOTCOME_IDNUM_11162022_0
if STACKOVERFLOWDOTCOME_IDNUM_11162022 exist it will rename to STACKOVERFLOWDOTCOME_IDNUM_11162022_0
it will add _0 at the last part.
One way to do it is to write a method that extracts the directory path, name, and extension of the file from a string that represents the full file path. Then we can create another variable to act as the "counter", which we'll use to add the number at the end of the file name (before the extension). We can then create a loop that checks if the file exists, and if it doesn't we'll increment the counter, insert it into the name, and try again.
For example:
public static string GetUniqueFileName(string fileFullName)
{
var path = Path.GetDirectoryName(fileFullName);
var name = Path.GetFileNameWithoutExtension(fileFullName);
var ext = Path.GetExtension(fileFullName);
var counter = 0;
// Keep appending a new number to the end of the file name until it's unique
while(File.Exists(fileFullName))
{
// Since the file name exists, insert an underscore and number
// just before the file extension for the next iteration
fileFullName = Path.Combine(path, $"{name}_{counter++}{ext}");
}
return fileFullName;
}
To test it out, I created a file at c:\temp\temp.txt. After running the program with this file path, it came up with a new file name: c:\temp\temp_0.txt
i need to create a (.txt) file on my application root on Xamarin.ios, so a need to store in memory a String, contain a UserName, after the user logged in, I can use each String to run a "httprequest" to my mySql database online. Similar procedure to the sessions in PHP, but client side and in C#.. Thanks you. I just try, with cookie, but I need to access at the UserName in every class and in every storyBoard.
I just try to write a JSON file serializable:
String NU = "NomeUtente=" + NomeUtente.Text;
string json = JsonConvert.SerializeObject(NU, Formatting.Indented);
System.IO.File.WriteAllText(#"/558gt.txt", json);
but Xamarin.ios throw a exception:
SystemUnauthorizedAccessexception -->
access to the path /558gt.txt denied.
If you need store data, use Xamarin.Essentials.SecureStorage
Check documentation
Thanks you. I read the documents on the ios file system and managed to write the portion of code necessary for reading and writing the Session file containing the username.
try {
//creo il file nella sandbox maledetta di iOS
//create file Session
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, "Session.txt");
//filename contiene la path completa di dove sta il file
File.WriteAllText(filename, NomeUtente.Text);
}
catch (Exception) {
label1.Text = "Errore generico.";
}
and now I read the file, in a separated class and storyboard:
//Recupero il nomeutente
var documents = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
var filename = Path.Combine(documents, "Session.txt");
var NomeUtente = File.ReadAllText(filename); //contiene il NomeUtente
I'm using SSIS and a script task in C#.
I have a FOR EACH Loop that looks into a folder and assigns the full path and file name of each file found to a variable called FileNameFound which in turn is then assigned to a variable called filepath within the Script Task.
I also have a Project parameter that stores an output path, this is being assigned to 'newFilepath' within the Script Task.
Using some other code I then Encrypt the csv file.
Bottom line is, I need the output to go into a different folder then where it was found but retain the same filename.
e.g.
find a file: c:\folder\test.csv
encrypt and output to c:\folder\new folder\test.csv
I need newFilepath to be the variable $Project::CSV_OutputFolder + test.csv
I am trying to incorporate GetFileNameWithoutExtension(String) but keep receiving the error:
The name 'GetFileNameWithoutExtension' does not exist in the current context
This is my code:
public void Main()
{
// Get the filepath of the file that needs to be encrypted.
string filepath = Dts.Variables["FileNameFound"].Value.ToString();
// build output path
string newFilepath = Dts.Variables["$Package::$Project::CSV_OutputFolder"].Value.ToString() + GetFileNameWithoutExtension(Dts.Variables["FileNameFound"].Value.ToString())+ ".csv";
// Get password from SSIS variable
string encryptionKey = Dts.Variables["EncryptionKey"].ToString();
// Create an encrypted copy of the file
Encrypt(filepath, newFilepath, encryptionKey);
// Close Script Task
Dts.TaskResult = (int)ScriptResults.Success;
}
What am I missing?
I got it working. I change the For Each to just retrieve the filename only then amended my code:
public void Main()
{
// Get the filepath of the file that needs to be encrypted.
string filepath = Dts.Variables["Unencrypted_Folder"].Value.ToString() + Dts.Variables["FileNameFound"].Value.ToString();
// build output path
string newFilepath = Dts.Variables["$Project::CSV_OutputFolder"].Value.ToString() + Dts.Variables["FileNameFound"].Value.ToString();
// Get password from SSIS variable
string encryptionKey = Dts.Variables["EncryptionKey"].ToString();
// Create an encrypted copy of the file
Encrypt(filepath, newFilepath, encryptionKey);
// Close Script Task
Dts.TaskResult = (int)ScriptResults.Success;
}
Path.GetFileNameWithoutExtension(Dts.Variables["FileNameFound"].Value.ToString())
as it is static class in System.IO namespace.
Hello everyone and well met! I have tried a lot of different methods/programs to try and solve my problem. I'm a novice programmer and have taken a Visual Basic Class and Visual C# class.
I'm working with this in C#
I started off by making a very basic move file program and it worked fine for one file but as I mentioned I will be needing to move a ton of files based on name
What I am trying to do is move .pst (for example dave.pst) files from my exchange server based on username onto a backup server in the users folder (folder = dave) that has the same name as the .pst file
The ideal program would be:
Get files from the folder with the .pst extension
Move files to appropriate folder that has the same name in front of the .pst file extension
Update:
// String pstFileFolder = #"C:\test\";
// var searchPattern = "*.pst";
// var extension = ".pst";
//var serverFolder = #"C:\test3\";
// String filename = System.IO.Path.GetFileNameWithoutExtension(pstFileFolder);
// Searches the directory for *.pst
DirectoryInfo sourceDirectory = new DirectoryInfo(#"C:\test\");
String strTargetDirectory = (#"C:\test3\");
Console.WriteLine(sourceDirectory);
Console.ReadKey(true);>foreach (FileInfo file in sourceDirectory.GetFiles()) {
Console.WriteLine(file);
Console.ReadKey(true);
// Try to create the directory.
System.IO.Directory.CreateDirectory(strTargetDirectory);
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
This is just a simple copy procedure. I'm completely aware. The
Console.WriteLine(file);
Console.ReadKey(true);
Are for verification purpose right now to make sure I'm getting the proper files and I am. Now I just need to find the folder based on the name of the .pst file(the folder for the users are already created), make a folder(say 0304 for the year), then copy that .pst based on the name.
Thanks a ton for your help guys. #yuck, thanks for the code.
Have a look at the File and Directory classes in the System.IO namespace. You could use the Directory.GetFiles() method to get the names of the files you need to transfer.
Here's a console application to get you started. Note that there isn't any error checking and it makes some assumptions about how the files are named (e.g. that they end with .pst and don't contain that elsewhere in the name):
private static void Main() {
var pstFileFolder = #"C:\TEMP\PST_Files\";
var searchPattern = "*.pst";
var extension = ".pst";
var serverFolder = #"\\SERVER\PST_Backup\";
// Searches the directory for *.pst
foreach (var file in Directory.GetFiles(pstFileFolder, searchPattern)) {
// Exposes file information like Name
var theFileInfo = new FileInfo(file);
// Gets the user name based on file name
// e.g. DaveSmith.pst would become DaveSmith
var userName = theFileInfo.Name.Replace(extension, "");
// Sets up the destination location
// e.g. \\SERVER\PST_Backup\DaveSmith\DaveSmith.pst
var destination = serverFolder + userName + #"\" + theFileInfo.Name;
File.Move(file, destination);
}
}
System.IO is your friend in this case ;)
First, Determine file name by:
String filename = System.IO.Path.GetFileNameWithoutExtension(SOME_PATH)
To make path to new folder, use Path.Combine:
String targetDir = Path.Combine(SOME_ROOT_DIR,filename);
Next, create folder with name based on given fileName
System.IO.Directory.CreateDirectory(targetDir);
Ah! You need to have name of file, but with extension this time. Path.GetFileName:
String fileNameWithExtension = System.IO.Path.GetFileName(SOME_PATH);
And you can move file (by File.Move) to it:
System.IO.File.Move(SOME_PATH,Path.Combine(targetDir,fileNameWithExtension)
Laster already show you how to get file list in folder.
I personally prefer DirectoryInfo because it is more object-oriented.
DirectoryInfo sourceDirectory = new DirectoryInfo("C:\MySourceDirectoryPath");
String strTargetDirectory = "C:\MyTargetDirectoryPath";
foreach (FileInfo file in sourceDirectory.GetFiles())
{
file.MoveTo(strTargetDirectory + "\\" + file.Name);
}
I have a program that's writing to a log file called "appname_yyyyMMdd.log", where appname is the name of my app, and yyyyMMdd is the current date; a sample log file name might be "loglistener_20110615.log" . Anyway, my app creates the log file fine, and it updates it as planned. However, once the date changes, the app doesn't log anything, and it doesn't create a new file. In other words, since today is 6/15, I need it to create a file called "loglistener_20110616.log" after midnight tonight, and I need it to continue logging to that new file.
Here are code excerpts:
public static void LogInfo(string format, params object[] args)
{
lock (_logLock)
{
using (StreamWriter sw = File.AppendText(GetLogPath()))
{
sw.WriteLine(GetTimeStamp() + String.Format(format, args));
}
}
}
private static string GetLogPath()
{
string appName = "loglistener";
string today = DateTime.Today.ToString("yyyyMMdd");
string fileName = appName + "_" + today + ".log";
string fullLogPath = AppDomain.CurrentDomain.BaseDirectory + fileName;
return fullLogPath;
}
I checked this similar question, but that question describes a different scenario (with a non-applicable fix).
UPDATE - Just in case googlers land on this page, I later discovered a different cause altogether w/ this. My log is logging info from an email-listening service. The service itself had a problem where it was timing out after a half-hour. So, my problem wasn't w/ CreateText / AppendText... My problem was there was nothing to log. Very annoying, but I hope other people won't be misled by this question/answer.
You should check to make sure that the file exists first.
From the File.AppendText Documentation
Type: System.IO.StreamWriter A
StreamWriter that appends UTF-8
encoded text to an existing file.
public static void LogInfo(string format, params object[] args)
{
lock (_logLock)
{
using (StreamWriter sw = File.Exists(GetLogPath) ? File.AppendText(GetLogPath()) : File.CreateText(GetLogPath())
{
sw.WriteLine(GetTimeStamp() + String.Format(format, args));
}
}
}
Try that instead
After looking at the comments and re-reading the documentation.
File.AppendText
Should always work, regardless of file existence.