C# Creating a text file contains the error logs - c#

I have created a text file to save the error in that created file. I have a button which, once pressed, generates an error which should be saved to the file. But if I press the button twice, it will overwrite the first error generated, because the contents of the file are overwritten. I want to generate a another separate file to save the new error. A new file should be generated for each new error.
Thanks in advance

Simple use: FileExists Method and then if it exists pick a new name. Alternatively you could just append to the file.
PSUDO:
public string checkFileName(string fileName){
if(File.Exists(fileName)){
/Pick a new one
newFileName= fileName + DateTime.Now.ToLongDateString()
return checkFileName(newFileName)
}
return fileName
}
This could be the perfect link for you How to Open and Append a log file

You can add time stamp in filename, in this case you would get new file each time.

private void SaveErrorMessage(string errorMessage)
{
string errorFile = null;
for( int x = 0; x < Int32.MaxValue; ++x )
{
errorFile = string.Format(CultureInfo.InvariantCulture, "error-{0}.txt", x);
if( !System.IO.File.Exists(errorFileTest) )
{
break;
}
}
File.WriteAllText(errorFile, errorMessage);
}
This will overwrite the last file after you've had Int32.MaxValue files, but that'll take a while.
An alternative (and probably better) approach would be to simply append to the file, rather than creating a new one.
You may also want to consider using a more robust logging solution, such as log4net.

Creating file in C# is probably what you're looking for.

So you want to generate a unique file name for each error that occurs in your program? Probably the easiest way to accomplish this is to use the date/time when the error occured to name the file. In the function where you are writing to the file you will want to name the file like this:
string filename = LogPath + DateTime.Now.ToString("yyyyMMdd.HHmmss") + ".err";
Where LogPath is the path to the folder you want to write the error files to.

Related

copy or move replace file and update version sharepoint CSOM

hi im using method for copy or move file on sharepoint. but i want to ask how to implement when it's duplicated it automatically replace and update version?
i've been try with this function but it's always
Microsoft.SharePoint.Client.ServerException: 'The destination file
already exists
public void CopyFile(string SrcUrl, string DestUrl)
{
MoveCopyOptions option = new MoveCopyOptions();
option.KeepBoth = false;
MoveCopyUtil.CopyFile(this.clientContext,SrcUrl,DestUrl,true,option);
this.clientContext.ExecuteQuery();
}
And my src
http://win-e636ggi1v13:55555/sites/srsrms/SRS%20Documents/Finance/fredytest/License%20Management.csv
and my Destination file
http://win-e636ggi1v13:55555/sites/srsrms/SRS%20Documents/Finance/paidi/Finance%20Folder/License%20Management.csv
#Mister Fredy,
Please set 'KeepBoth' to false and keep 'Overwrite' with true.
With the above settings, it will overwrite the existing file.
When both are false, it will prompt below error:
Another scenario is :
the destination file is not overwritten and a new file with a duplicate avoiding filename is created - i.e. a number is appended to the filename to avoid a duplicate.
BR

C# FileInfo.Length Property for .txt file vs .csv file

I am new to C# and new to Visual Studio. I am about half way through a 16 week class in C# using Visual Studio. I felt like I may have learned enough to understand this piece of code from work and modify it. So far I have been able to understand most of it (after many hours, and using google a lot). However, there are a few places that have me stumped... Or maybe the original programmer didn't use very good logic? I don't know... See the code below:
//This is just a piece of the code... there are hundreds of lines of code above this
private static void OnSizeChange(object source, FileSystemEventArgs e)
{
try
{
// SET PATHS FROM WATCHER
String filePath = e.FullPath;
FileInfo infoForPath = new FileInfo(e.FullPath);
//CHECK FOR TEXT FILE IN ORDER TO VERIFY SIZE TO CONFIRM NEW EMPTY FILE WAS NOT CREATED
String txtExt = ".txt";
Boolean isTxt = e.FullPath.Contains(txtExt);
//Length gets the size, in bytes, of the current file.
if (!isTxt && infoForPath.Length > 5 || isTxt && infoForPath.Length > 0)
What you can not see here is that the file will either be a .txt file or a .csv file. My question is about the if statement.
What is the if statement checking?
From what I can gather, it is checking to see if there is a ".txt" in the file path && the length of the file in bytes is "> 5" (for a non .txt file) or "> 0" (for a .txt file).
What is the reason for the "5" and the "0"?
Is there some inherent reason for these numbers as pertains to .txt and .csv files?
If it helps, i found this code online, which is similar and could be used for testing I think from a C# command prompt application.
using System;
using System.IO;
class Program
{
static void Main()
{
const string fileName = #"C:\programs\file.txt";
// Part 1: create new FileInfo get Length.
FileInfo info = new FileInfo(fileName);
long length = info.Length;
// Part 2: print length in bytes.
Console.WriteLine("LENGTH IN BYTES: {0}", length);
}
}
Output
LENGTH IN BYTES: 60
To start Boolean isTxt = e.FullPath.Contains(txtExt); is error prone and not the best way to do this.
You should instead get the extension by doing var fileExtenstion = infoForPath.Extension
this will get you the extension of the file. For more info about this look here. Now that you have the extension you can check if the extension is .txt and return a bool or change how you're if statement works.
The reason for checking for the length of 0 for text files is because text files contain no data (length) when they are empty. I don't know for sure but CSV files may have a default length of 5. You can use the console app code you posted if you want to check this

Program crashing due to IOException

I'm new to C# and I'm trying to create a simple program that asks the user to input a filename and some text to then be saved to the newly created file. Maybe I went too fast and did not learn everything I should have about file manipulation. Any help would be appreciated.
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = folderPath + fileName;
File.Create(filePath);
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
var inputTextUser = Console.ReadLine();
File.AppendAllText(filePath, inputTextUser);
When the application crashes on line 29, I get this message:
System.IO.IOException the process cannot access the file because it is being used by another process.
Line 29 which is the AppendAllText line.
The problem here is that you (your application) still "hold" that file. Actualy, you don't need to create that file, before you write something to it. As stated here AppendAllText will create a file, if it does not exists, so just remove that line, where File.Create(filePath);
You need to close/dispose the previous stream that accessed the file because File.Create keeps the file open and returns a FileStream object.
I checked your code and this solution works.
File.Create(filePath).Close();
OR/AND
File.Create(filePath).Dispose();
Rewrite your code like as
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = folderPath + fileName;
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
string[] lines = new string[1];
var inputTextUser = Console.ReadLine();
lines[0] = inputTextUser;
//File.AppendAllText(filePath, inputTextUser);
File.WriteAllLines(filePath, lines);
You can write without array
File.WriteAllText(filePath, inputTextUser);
The issue is that the File.Create method keeps the file opened thus the Operating System puts a lock on it. The method returns a FileStream object you can use for read/write access. Before you can write to that file with a different method (such as File.WriteAllText - this method will try to open an already opened file), the FileStream object must be first disposed. See this MS reference.
Simply commenting out that line of code will fix the IOException.
In general, File.Create is not a very commonly used method and is generally used in more specialized cases. If possible, the prefered way is to construct your text file in memory using a string or a StringBuilder then output the contents to file. In your case, that is definitely the approach you want to take. As others have mentioned, you would use File.WriteAllText. It will create the file if it does not exist, or replace the contents of the already existing file. If you want to keep previous content, the use File.AppendAllText as you did in your question. This method will create the file if it does not exist or append the text to the end of the previous content.
Try this:
Console.WriteLine("Enter name of file then add .txt");
var fileName = Console.ReadLine();
var folderPath = #"C:\Users\Treppy\Desktop\Megatest\";
var filePath = System.IO.Path.Combine(folderPath, fileName);
if (!File.Exists(filePath))
{
File.WriteAllText(filePath, "");
}
Console.WriteLine(filePath);
Console.WriteLine("Enter the text you want to save to that file");
var inputTextUser = Console.ReadLine();
File.AppendAllText(filePath, inputTextUser);
That'll stop the File.Create holding the file open with the OS.

how to Save File using C# Windows Application

I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));

getting file name and moving it

string fName = Path.GetFileName(tempPaths[z]);
if (!File.Exists(subAch + fName))
{
File.Move(tempPaths[z], subAch + fName);
Console.WriteLine("moved!!! from " + tempPaths[z] + " tooooo ");
}
tempPaths is a list with all the image file paths. e.g. ./images/image4.jpg
subAch is a directory string.
I wish to get the file name of the file then move them to another directory. But with the code above i kept getting error: file is being used by other process.
Is there anyway which get the file name and move them? I have tried fileStream but was confused by it.
Please advice.
Thank you!
Your code should work just fine. You just need to figure out who is locking the files.
I'd put the code inside the if-block in a try-catch block to deal with the locked files.
I will also recommend you to use Path.Combine instead of dir + file.
One thing: you are checking if subAch + tempPaths[z] exists, yet you are copying to a different location; subAch + fName.
File is being used by another process means exactly that. Someone/something is already using the file, so can't move it. You can always catch the error and moving everything else?
I have use a non-ideal way to grab the file name and move the files to another place.
tempPaths.AddRange(Directory.GetFiles(rawStorePath, filter, SearchOption.AllDirectories));
The code above gets all the directories of all the files in the folder set. The outcome with be something like this. tempPaths is a List.
"./images/glass_numbers_5.jpg"
"./images/G.JPG"
"./images/E.JPG"
"./images/F.JPG"
"./images/glass_numbers_0.jpg"
"./images/C.JPG"
"./images/B.JPG"
"./images/A.JPG"
"./images/D.JPG"
"./images/glass_numbers_7.jpg"
then after i use a loop to grab the file names.
for (int i = 0; i < tempPaths.Count; i++)
{
//Getting the original names of the images
int pLength = rawStorePath.Length;
string something = tempPaths[i].Remove(0, pLength);
if (!_tfileName.ContainsKey(tempPaths[i]))
{ _tfileName.Add(tempPaths[i], something); }
}
rawStorePath is the path of the targeted path e.g.: ./images/
tempPath[i] e.g. : ./images/G.JPG
So with the length i remove the letters and get the file name back.
Please advice me for a ideal way to do this if there is any.
Thanks!

Categories

Resources