This question already has answers here:
IOException: The process cannot access the file 'file path' because it is being used by another process
(12 answers)
Closed 1 year ago.
I'm a student who just started learning C#,
I'm trying to create Sign-Up and Login functions using text files, and save details that the user inputs into the textfile, but when I run my function again it rewrites what is already there instead of starting a new line.
This is a bit of my code that is important
using System;
using System.IO;
namespace SDD_Assessment_2
{
class Program
{
static void Main(string[] args)
{
//Write();
//GetTime();
var privInfo = SignUp();
var FullName = Profile(privInfo);
Profile(privInfo);
//Test(FullName);
}
const string filename = "Workout.txt";
static string[] SignUp()
{
string[] privinfo = new string[4];
Console.Write("First Name: ");
privinfo[0] = Console.ReadLine();
Console.Write("Last Name: ");
privinfo[1] = Console.ReadLine();
Console.Write("Email: ");
privinfo[2] = Console.ReadLine();
Console.Write("Password: ");
privinfo[3] = Console.ReadLine();
StreamWriter NewAccount = new StreamWriter(filename);
//NewAccount.WriteLine(privinfo[0] + "," + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
NewAccount.Close();
return privinfo;
}
}
}
When I run it right now, it says "System.IO.IOException: The process cannot access the file 'filename' because it is being used by another process."
Your code is mostly correct. You need to change
StreamWriter NewAccount = new StreamWriter(filename);
//NewAccount.WriteLine(privinfo[0] + "," + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
NewAccount.Close();
to just
File.AppendAllText(filename, privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
Your allocation of NewAccount opens a stream to the file, which keeps the file handle open. That means your File.AppendAllText can't complete, because the file was previously opened in a non-sharing mode.
If you had deleted File.AppendAllText you wouldn't get the error, but you'd end up with a zero byte file as you wrote nothing to the stream.
As you are not using NewAccount at all, removing those lines will allow File.AppendAllText to complete without error, and... append all the text you expect, which would be the values for first and last names, email and password.
I try, it work
Don't open stream when you not used
File name include directory
class Program
{
static void Main(string[] args)
{
SignUp();
}
const string filename = "Workout.txt";
static string[] SignUp()
{
string[] privinfo = new string[4];
privinfo[0] = "First Name:";
privinfo[1] = "Last Name: ";
privinfo[2] = "Email: ";
privinfo[3] = "Password: ";
File.AppendAllText(Path.Combine(Environment.CurrentDirectory, filename), privinfo[0] + ", " + privinfo[1] + "," + privinfo[2] + "," + privinfo[3] + Environment.NewLine);
return privinfo;
}
}
Run 2 times
file content is
First Name:, Last Name: ,Email: ,Password:
First Name:, Last Name: ,Email: ,Password:
Related
I'm getting a OutOfMemory exception when running the following code, it happens on the File.ReadLines line, it processes most files fine until it hits larger files.
It's consistantly using tons of memory and cpu during the whole process though.
The file it crashed on is only 156,000KB, which is 156mb
static void Main(string[] args)
{
Console.CursorVisible = false;
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Connected to the Cassandra Database");
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
string filepath = #"C:\Users\admin\Desktop\wecrack lists";
DirectoryInfo directory = new DirectoryInfo(filepath);
int fileCount = 0;
var client = new MongoClient("mongodb://localhost:27017");
var database = client.GetDatabase("cracking");
var collection = database.GetCollection<Password>("passwords");
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
List<Password> entitys = new List<Password>();
foreach (string line in File.ReadLines(filepath + #"\" + file.ToString()))
{
entitys.Add(new Password { password = line });
}
collection.InsertManyAsync(entitys);
}
Console.WriteLine();
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Finished inserting records, press any key to get the count.");
Console.ReadKey(true);
while (true)
{
Console.ReadKey(true);
}
}
Try batching your updates. That way you won't have all that data in memory at the same time. It may also help you not totally lock up your database.
...
foreach (var file in directory.GetFiles("*"))
{
fileCount++;
Console.WriteLine(" [" + DateTime.Now.ToShortTimeString() + "]" + " Working through file: {" + file + "} {" + fileCount + "/" + directory.GetFiles("*").Count() + "}");
System.IO.StreamReader file = new System.IO.StreamReader(filepath + #"\" + file.ToString());
while(!file.EndOfStream)
{
int passwordBatchCount = 0;
List<Password> entitysBatch = new List<Password>();
while ((string line = file.ReadLine()) != null && passwordBatchCount < BATCH_SIZE)
{
entitysBatch.Add(new Password { password = line });
passwordBatchCount++;
}
collection.InsertManyAsync(entitysBatch);
}
file.Close();
}
}
...
The process cannot access the file 'file path' because it is being used by another process.
i have found these 2 question
File being used by another process after using File.Create()
and
Does File.AppendAllText close the file after the operation
this is an API that i have and need to save every request that comes in and the result that goes out,
there might be more than one request that a give time
my code
public static void SaveTheRequestAndResponse(string type, SearchRequest searchRequest = null, dynamic result = null)
{
var FilePath = AppDomain.CurrentDomain.BaseDirectory + #"SearchRequest";
bool exists = Directory.Exists(FilePath);
if (!exists)
{
var stream = Directory.CreateDirectory(FilePath);
}
if (type == "request")
{
string Space = ", ";
StringBuilder request = new StringBuilder();
request.Append("Search Id : " + searchRequest.ID);
request.Append(Space + "Company Name : " + searchRequest.CompanyName);
request.Append(Space + "Country Code : " + searchRequest.CountryCode);
request.Append(Space + "Search Type : " + searchRequest.SeacrhType);
request.Append(Space + "Request Time : " + DateTime.Now + Environment.NewLine);
var DataToBeSave = request.ToString();
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
else
{
string Space = ", ";
StringBuilder SearchResult = new StringBuilder();
SearchResult.Append("The result for Request" + Space);
SearchResult.Append("Search Id : " + searchRequest.ID + Space);
SearchResult.Append("States Code : " + result.StatusCode + Space);
SearchResult.Append("Result Time : " + DateTime.Now + Environment.NewLine);
var DataToBeSave = SearchResult.ToString();
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
}
my understanding is that the File.AppendAllText will close after the Operation so why do i get the this error
my code is having an race condition, and this is because the API is being call by more than one user at each given time, even that
System.IO.File.AppendAllText(FilePath + #"\" + "FileNAme" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
will close after the Operation, it still need time do its work and only one connection can be open at each give time so the thread need to be lock and that can be done by
private static Object thisLock = new Object();
lock (thisLock)
{
System.IO.File.AppendAllText(FilePath + #"\" + "DandB" + DateTime.Now.ToString("dd-MM-yyyy") + ".txt", DataToBeSave + Environment.NewLine);
}
Thanks to Abydal
So I'm trying to exit a console application IF a parameter check fails, however, I still want it to log to a file. The logging to a file works fine as long as all the parameters are good. However, when a parameter check fails and hits the System.Environment.Exit(0) portion, the log file is still completely empty. Here's the code so far. Please help, I've tried everything I could think of.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
namespace I2C_File_Splitter
{
class Program
{
static void Main(string[] args)
{
//get command line input paramaters
using (StreamWriter log = File.AppendText("Splitter_log.txt"))
{
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER STARTED ****************************************************************");
log.WriteLine(DateTime.Now + " FILE: " + args[0] + " DESTINATION: " + args[1] + " MAX COUNT PER FILE: " + args[2]);
if (args.Length == 0)
System.Environment.Exit(0);
string originalFile = args[0];
string destination = args[1];
int fileLength = Convert.ToInt32(args[2]);
string fileName;
string fileExtension;
string line;
int fileNumber = 1;
if (!File.Exists(originalFile))
{
log.WriteLine(DateTime.Now + " Error: Transfund file not found for: " + args[0]);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
if (!Directory.Exists(destination))
{
log.WriteLine(DateTime.Now + " Error: destination directory not found for: " + args[1] );
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
if (fileLength < 0)
{
log.WriteLine(DateTime.Now + " Error: file length must be greater than 0. Incorrect value " + args[2]);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
System.Environment.Exit(0);
}
//get file name and file extension
fileName = Path.GetFileNameWithoutExtension(originalFile);
fileExtension = Path.GetExtension(originalFile);
StreamReader file = new StreamReader(originalFile);
log.WriteLine(DateTime.Now + " processing: " + fileName);
string header = file.ReadLine(); //get first line
while ((line = file.ReadLine()) != null)
{
StreamWriter newFile = new StreamWriter(destination + "\\" + fileName + "_" + fileNumber.ToString() + fileExtension);
newFile.WriteLine(header);
newFile.WriteLine(line);
int counter = 1;
while (counter < fileLength)
{
line = file.ReadLine();
if (line == null)
break;
newFile.WriteLine(line);
counter++;
}
newFile.Close();
log.WriteLine(DateTime.Now + " " + fileName + "_" + fileNumber.ToString() + fileExtension + " created. Card count: " + counter);
fileNumber++;
}
log.WriteLine(DateTime.Now + " Processing completed: " + fileName);
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
}
}
}
}
When you call Environment.Exit, you're telling it to terminate your program immediately.
Your "log" stream never gets flushed (which would happen when you reach the end of the using block), and so nothing gets a chance to be written to the file.
Try flushing the stream before calling exit.
if (!Directory.Exists(destination))
{
log.WriteLine(DateTime.Now + " Error: destination directory not found for: " + args[1] );
log.WriteLine(DateTime.Now + " ******************************************** SPLITTER ENDED ****************************************************************");
// write all pending log messages to the file
log.Flush();
System.Environment.Exit(0);
}
I want to log Exception in case of error on network. I have made changes in global.asax file and generated log file in it. The code works fine on localhost but when I upload the dll of global.asax file on another server and change the web config according to network credentials similar to the localhost. In case of error the method doesnot seem to work nor the file is created to write the exception. Please help
void Application_Error(object sender, EventArgs e)
{
// Code that runs when an unhandled error occurs
try
{
DffUtility.AddCookie("verystart", "Very start of error");
Exception exc = Server.GetLastError();
Uri refurl = Request.UrlReferrer;
DffUtility.AddCookie("star655", "getting exception start");
string networkLogFolderPath = ConfigurationManager.AppSettings["Logpath"] + "\\" + DffUtility.WebSiteInfo.Folder + "\\" + DffUtility.WebSiteInfo.ThemeName + "\\";
DffUtility.AddCookie("path", networkLogFolderPath.ToString());
Network.connectToRemote(ConfigurationManager.AppSettings["Logpath"],
ConfigurationManager.AppSettings["networkusername"],
ConfigurationManager.AppSettings["pass"]);
string LogFolderPath = HttpContext.Current.Server.MapPath("~/ExceptionLogFiles/");
string filePath = networkLogFolderPath;
string stacktracemessage, stacktrace, Errormsg, extype, exurl;
stacktracemessage = (exc.InnerException).Message;
stacktrace = exc.ToString();
Errormsg = exc.GetType().Name.ToString();
extype = exc.GetType().ToString();
exurl = HttpContext.Current.Request.Url.ToString();
if (!System.IO.Directory.Exists(System.IO.Path.GetDirectoryName(filePath)))
System.IO.Directory.CreateDirectory(System.IO.Path.GetDirectoryName(filePath));
if (DffUtility.Country > 0)
{
if (DffUtility.RegionArea > 0)
{
if (DffUtility.RegionCity > 0)
{
if (DffUtility.ProdID > 0)
{
filePath = (filePath + "Product_" + DffUtility.ProdID + "_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
else
{
filePath = (filePath + "City_" + DffUtility.RegionCity + "_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Area_" + DffUtility.RegionArea + "_" + DffUtility.Country + ".txt");
}
}
else
{
filePath = (filePath + "Country_" + DffUtility.Country + ".txt");
DffUtility.AddCookie("start8", "After generating product file");
}
}
System.IO.File.Create(filePath).Dispose();
using (System.IO.StreamWriter sw = System.IO.File.AppendText(filePath))
{
string logFormat = Environment.NewLine + " " + Environment.NewLine;
DffUtility.AddCookie("start6", "in");
string error = "Error Message:" + " " + Errormsg + logFormat + "Exception Type:" + " " + extype + logFormat + " Error Page Url:" + " " + exurl + logFormat + " StackTraceMessage:" + " " + stacktracemessage + logFormat + " StackTrace:" + " " + stacktrace + logFormat + " " + refurl + logFormat;
sw.WriteLine("-----------Exception Details on " + " " + DateTime.Now.ToString() + "-----------------");
sw.WriteLine("-------------------------------------------------------------------------------------");
sw.WriteLine(error);
sw.WriteLine(logFormat);
sw.Flush();
sw.Close();
DffUtility.AddCookie("start4", " after getting generated log");
}
It's because your application runs under NETWORK SERVICE account (by default) and don't have permissions to write in ExceptionLogFiles folder. Add user Everyone in folder properties and grant him that permission
I have the following bits of code:
public static void WriteHTML(string cFile, List<Movie> mList)
{
int lineID = 0;
string strMovie, strGenre, tmpGenre = null;
// initiates streamwriter for catalog output file
FileStream fs = new FileStream(cFile, FileMode.Create);
StreamWriter catalog = new StreamWriter(fs);
string strHeader = "<style type=\"text/css\">\r\n" + "<!--\r\n" + "tr#odd {\r\n" + " background-color:#e2e2e2;\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "\r\n" + "tr#even {\r\n" + " vertical-align:top;\r\n" + "}\r\n" + "div#title {\r\n" + " font-size:16px;\r\n" + " font-weight:bold;\r\n" + "}\r\n" + "\r\n" + "div#mpaa {\r\n" + " font-size:10px;\r\n" + "}\r\n" + "\r\n" + "div#genre {\r\n" + " font-size:12px;\r\n" + " font-style:italic;\r\n" + "}\r\n" + "\r\n" + "div#plot {\r\n" + " height: 63px;\r\n" + " font-size:12px;\r\n" + " overflow:hidden;\r\n" + "}\r\n" + "-->\r\n" + "</style>\r\n" + "\r\n" + "<html>\r\n" + " <body>\r\n" + " <table>\r\n";
catalog.WriteLine(strHeader);
foreach (Movie m in mList)
{
strMovie = lineID == 0 ? " <tr id=\"odd\" style=\"page-break-inside:avoid\">" : " <tr id=\"even\" style=\"page-break-inside:avoid\">";
catalog.WriteLine(strMovie);
foreach (string genre in m.Genres)
tmpGenre += ", " + genre;
try
{ strGenre = tmpGenre.Substring(2); }
catch (Exception)
{ strGenre = null; }
strMovie = " <td>\r\n" + " <img src=\".\\images\\" + m.ImageFile + "\" width=\"75\" height=\"110\">\r\n" + " </td>\r\n" + " <td>\r\n" + " <div id=\"title\">" + m.Title + "</div>\r\n" + " <div id=\"mpaa\">" + m.Certification + " " + m.MPAA + "</div>\r\n" + " <div id=\"genre\">" + strGenre + "</div>\r\n" + " <div id=\"plot\">" + m.Plot + "</div>\r\n" + " </td>\r\n" + " </tr>\r\n";
catalog.WriteLine(strMovie);
lineID = lineID == 0 ? 1 : 0;
}
catalog.WriteLine(" </table>\r\n" + " </body>\r\n" + "</html>");
catalog.Close();
}
public static void WritePDF(string cFile, string pdfFile)
{
// Sets up PDF to write to
EO.Pdf.HtmlToPdf.Options.PageSize = new SizeF(8.5f, 11f);
EO.Pdf.HtmlToPdf.Options.OutputArea = new RectangleF(0.5f, .25f, 7.5f, 10.25f);
HtmlToPdf.ConvertUrl(cFile, pdfFile);
}
My HTML file writes fine, but when it tried to convert the HTML file to PDF I get an exception that it times out.
I did a test previously, and had it convert the code (not the file) within the WriteHTML function and it worked great. I have confirmed that the cFile exists and is a valid file (created previously in WriteHTML). The path to pdfFile is valid, and the documentation does not state the file needs to already exist (.ConvertHTML did not need an existing file).
Only thing I can think of is that the catalog.html file isn't released and ready to read yet. I made sure I closed it in the WriteHTML function. How can I test that the file is ready to be read?
Tried setting .MaxLoadWaitTime = 120000 with no luck.
Any clues would be greatly appreciated!
After a battery of further testing, and scouring the EO support forums, it appears to be a limitation of the free version of EO. It seems to have difficulty with HTML files over 3MB.
It's a shame since the EO product is very good, but not unfortunately not worth $250 IMO.