Writing a CSV log file - c#

I have a Winforms program that needs to log data points into a .CSV file. It's fairly simple, date/time and a double (the data), and go to the next line.
Here's what I have so far (not working, I get an error saying the file is busy/already open - however, it's empty)
if (!Directory.Exists(SavePath.Text + "\\LOG"))
Directory.CreateDirectory(SavePath.Text + "\\LOG");
string LogFileName = SavePath.Text + "\\LOG\\Seeing-Log-" + TimeNow.ToString("yyyy-MM-dd") + ".csv";
if (!File.Exists(LogFileName))
File.Create(LogFileName);
string LogString = TimeNow.ToString("yyyy-MM-dd-_HH-mm-ss") + "," + FWHM_Value.ToString("F:");
File.AppendAllText(LogFileName, LogString + Environment.NewLine);
It's that last line that generates the error.
Any idea what I am doing wrong?
thanks
Steve

File.Create returns an open FileStream to the file that's just been created. Either change your code to work with FileStream in both the non-existent and existent file cases, or just close the file after creating it:
if (!File.Exists(LogFileName))
File.Create(LogFileName).Close();
But, of course, if you check the documentation for AppendAllText:
Appends the specified stringto the file, creating the file if it does not already exist.
You'll realise that the above two lines are completely redundant anyway and can be removed:
if (!Directory.Exists(SavePath.Text + "\\LOG"))
Directory.CreateDirectory(SavePath.Text + "\\LOG");
string LogString = TimeNow.ToString("yyyy-MM-dd-_HH-mm-ss") + "," + FWHM_Value.ToString("F:");
File.AppendAllText(LogFileName, LogString + Environment.NewLine);

You can even use the free looging tools. Here is one 'log4net'
You can also write the csv file using this. I am assuming currently you are not using logging tool. it will work for you without any code for implementation .
http://element533.blogspot.in/2010/05/writing-to-csv-using-log4net.html
Have a great day!!

Replace
File.Create(LogFileName);
with
File.Create(LogFileName).Close();
see this to create empty file.

The file is locked when you create it. Just update your code to this:
File.Create(LogFileName).Close();

Related

C# File.AppendAllText produces corrupted file

I am trying to append some lines to a *.doc file using:
foreach (var user in usersApproved)
File.AppendAllText(Server.MapPath(("..\\Files\\TFFiles\\" + tid + "\\" + file.Type + "\\")) + Path.GetFileName(file.Title), "Document Signed by: " + user.UserName + Environment.NewLine);
But it produces a corrupted file.
EDITS
I used this answer to produce a *.docx file. But when I try to append the lines I receive the error that "...the file is used by another process" so it fails
The machine is a server where I don't want to install Word/Office so Office Interop is not a viable option.
I do believe that what you need is the Document.Add method. You can read about it here: https://msdn.microsoft.com/en-us/library/microsoft.office.interop.word.documents.add(v=office.14).aspx
If I'm not mistaken, you are trying to treat your file as a common text file while the .doc is a MSWord document

File.Exists is returning false even though I can see the file C#

Issue
I have a function which lets the user edit an image when they do this I save this new image to a file to which they I save to the database etc ...
The issue comes as when I try and look for the file I just saved it says it does not exist but it does?
Code
Here I am saving the new file to the TEMP folder:
string newFullTempFolderURL = Path.Combine(Global.TempFolder, newFullFileName + ".png");
_image.Save(newFullTempFolderURL, System.Drawing.Imaging.ImageFormat.Png);
At this point when I check the folder the file is in the folder with the new image.
Then when I go on to uploading the file to the server (Using BITS) I do a check to make sure the file exists:
if (File.Exists(Path.Combine(Global.TempFolder + "\\" + newFullFileName)))
{
}
This then returns false (Not exists) when i can see the file with my own eyes!
Anyone had this same issue?
EDIT1:
newFullFileName already contains .png:
string newFullFileName = string.Format(oldFileName.Substring(0, oldFileName.IndexOf("_") + 1) + DateTime.Now.ToString(), "yyyyMMddhhmmss").Replace(#"/", "").Replace(" ", "").Replace(":", "") + ".png";
As per your edit you are added .png to newFullFileName.. then newFullTempFolderURL will add another .png to your file name.
So ti will become FILENAME.png.png it will return wrong.
remove .png from newfullFilename and
try below
if (File.Exists( Path.Combine(Global.TempFolder, newFullFileName))
{
}
your File.Exists does not contain the file extension as you manually added it when creating "newFullTempFolderURL". You need to append ".png" to the File.Exists check or better yet use File.Exists(newFullTempFolderURL); as it's already been pre-made.
EDIT1:
You are adding ".png" a second time. This is wrong, as the file created is ".png.png", and then you are checking to see if ".png" exists.

Run application | app say error

I try to run my game in my game launcher but it says:
Memory access violation
Code
String name = GetValue(File.ReadAllLines(Co), "lib-name" + DubDown);
System.Diagnostics.Process.Start(path + "\\Games\\" + name + "\\" + GetValue(File.ReadAllLines(Co), "lib-file" + DubDown));
String name = GetValue(File.ReadAllLines(Co), "lib-name" + DubDown);
Why are you reading all lines of a file, but the file name shown below is used?
Does the file contain the names of all the files you want to open?? I think you'll need a loop to do that
String name....
shown above is included in the code below twice when written here
... + name +....
and here (as the value of name)
....GetValue(File.ReadAllLines(Co), "lib-file" + DubDown));
Try writing this like this.
System.Diagnostics.Process.Start(path + "\\Games\\" + name);
Unfortunately, as noted above, you'll need to iterate through the contents of the file prior to getting the names from inside the file, as your first line of code portrays. Sort of.
I think you should post more of the code for better assistance.

Zip File Entry has custom file extension. C# claims it cannot open

Solution Found.
Thanks to everyone helping me, I found out what the root problem was. The .trl file had nothing to do with it. It was the path being created wrong. I was doing "TRLR" + Path, when it should have been "TRLR" + fileName. This was a stupid error on my part, and I apologize for wasting your time, but I appreciate the help!
I have a zip file given to us by a 3rd party. In this zip files are custom files. These are just text files with a different extension, which I assume is just to frustrate me.
I'm trying to open this files in my C# application, but it keeps throwing the error that the format is not supported.
Since these are just text files, I feel there must be some way for this to happen.
If anyone has any ideas, please let me know.
Code:
using (ZipArchive archive = ZipFile.OpenRead(_trailerName))
{
ZipArchiveEntry entry = archive.GetEntry(tableChanged + ".trl");
Stream ms = entry.Open(); //Here is what's causing the issue.
StreamReader reader = new StreamReader(ms);
string allLinesRead = reader.ReadToEnd();
string[] everyCell = allLinesRead.Split('|');
int numRecords = Convert.ToInt32(everyCell[1]);
int numChanged = getRecordNum(tableChanged);
Console.Write(numRecords + "/" + numChanged + " - " + tableChanged);
if (numChanged != numRecords)
{
_errorMessage += "Records updated do not match trailer. (" + numRecords + "/" + numChanged + ") Please check database. Table affected: " + tableChanged + Environment.NewLine;
}
}
Error:
The given path's format is not supported.
I know this is specific, but I need advice on what steps I can take to resolve this.
Thanks.
The native zip functionality of .NET is frequently lacking in terms of the ability to handle and modify zip files created by applications other than the windows zip tool. While the "zip" file is standardized, you still see a decent amount of variation on file headers and attributes.
I would suggest you look into DotNetZip (Ionic), which is a third party library that has very robust capabilities in terms of creating and opening zip files. I've found it to be much more forgiving and capable than the basic functionality that .NET gives you, and the code to open a zip is extremely similar to what you have.

Dynamically opening a doc file c#

I have been using this line of code for the past few weeks to dynamically open a doc file once the user has created it and its been working fine...
System.Diagnostics.Process.Start(#"C:\\Users\\peter\\Desktop\\" + txtEditTitle.Text + ".doc");
but today, for some reason it gives me the following error:
Can anybody help?
As you can read in the exception the file is not there. It would not be wrong to check if the file exists before opening it.
As per your screenshot, it shows file is not there. Check your path for the file and make sure file exists:
string strPath = "C:\\Users\\peter\\Desktop\\" + txtEditTitle.Text + ".doc";
// strPath=#"C:\Users\peter\Desktop\" + txtEditTitle.Text + ".doc";
if (File.Exists(strPath))
{
System.Diagnostics.Process.Start(strPath);
}

Categories

Resources