I know you are going to tell me that this question is stupid but I really cannot find a solution to delete my file.
In fact, I open a connection to an .add file (same style as SQL in a way) but afterwards I cannot delete it because it is used by another process which is the process of my application.
While doing some research on the internet I was able to find the solution to kill the process however if I do this it stops my application. Then I also found the GC collect but it doesn't work : /
There is my code :
try
{
string idClient = "parfilux";
string tableName = "ACT,ACF";
string dataSourceDBF = "C:/winbooks/data/parfilux";
string path = dataSourceDBF ;
string pathTemp = dataSourceDBF + "/CopyTempWebService/";
if (!Directory.Exists(pathTemp)) Directory.CreateDirectory(pathTemp);
string addFile = path + "/" + idClient + ".add";
File.Copy(addFile, pathTemp + idClient.ToUpper() + ".add");
File.Copy(addFile.Replace(".add", ".ai"), pathTemp + "/" + idClient.ToUpper() + ".ai");
File.Copy(addFile.Replace(".add", ".am"), pathTemp + "/" + idClient.ToUpper() + ".am");
tableName = tableName.Replace(" ", "");
string[] tables = tableName.Split(',');
string pathTable = null;
foreach (string tab in tables)
{
pathTable = path + "/" + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf";
File.Copy(pathTable, pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".dbf");
File.Copy(pathTable.Replace(".dbf", ".cdx"), pathTemp + idClient.ToUpper() + "_" + tab.ToUpper() + ".cdx");
}
AdsConnection dbfCo;
//dbfCo.Close();
dbfCo = new AdsConnection(#"data Source=" + dataSourceDBF + "/CopyTempWebService/" + idClient + ".add;User ID=admin;Password=;ServerType=Local;ReadOnly=true;pooling=true;TrimTrailingSpaces=true;ShowDeleted=TRUE;TableType=CDX;LockMode=COMPATIBLE");
dbfCo.Open();
//QueryDataDBF(tableName, idClient, false);
dbfCo.Close();
dbfCo.Dispose();
//Process process = Process.GetCurrentProcess();
//Console.WriteLine(process.MainModule);
//process.Kill();
//foreach(Process pro in process)
//{
// Console.WriteLine(pro);
// if(pro.ProcessName == pathTemp + idClient.ToUpper() + ".add")
// {
// pro.Kill();
// }
//}
//System.GC.Collect();
//System.GC.WaitForPendingFinalizers();
//File.Delete(pathTemp + idClient.ToUpper() + ".add");
Directory.Delete(dataSourceDBF + "/CopyTempWebService", true);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
I open a connection to my .add with the Advantage Data Provider library.
Do you have any idea to fix this problem ? thank you in advance ;)
Related
I can't seem to be able to delete files after a streamreader use, with a
"file can't be accessed because file is in use"
error in C#.
I may miss something but I don't know what, here is the code :
fileEntries = from fullFilename
in Directory.EnumerateFiles(#"Data\csv\pending")
select Path.GetFileName(fullFilename);
i = 1;
foreach (string file in fileEntries)
{
if(i == 1)
{
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.FileStream fs = System.IO.File.Create(folder + #"\create-user.csv"))
{
}
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; prenom; nom; username; pasword; email; question; reponse; GroupID");
}
string curfile = #"\create-user-archive.csv";
if(!(File.Exists(folder + curfile)))
{
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; prenom; nom; username; pasword; email; question; reponse; GroupID");
}
}
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\pending";
sb = new StringBuilder();
filef = new System.IO.StreamReader(folder + #"\create-user-" + i + ".csv");
line = filef.ReadLine();
while ((line = filef.ReadLine()) != null)
{
sb = new StringBuilder();
sb.AppendLine(line.Substring(0, line.Length));
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
}
i++;
sourceFile = System.IO.Path.Combine(#"Data\csv\pending", file);
File.Delete(sourceFile);
}
shouldn't the file stop being in use after the streamreader is finished? I tried using a function that waits until the file is unlocked to delete the file, but it is infinite, which means there is a never ending process that I must stop, but I don't see which one.
You need to close filef.
Wrapping the code in a using statement will automatically close the reader
using ( System.IO.StreamReader filef = new System.IO.StreamReader(folder + #"\create-user-" + i + ".csv") {
....yourcodehere
}
Alternatively, call filef.Close() when you are done with it (before you delete the file)
You have to close the streams you create to dispose the system resources. You can either use the Close method or the using pattern, as the classes implemented IDisposable interface. I would recommend you to the second option.
May have a look to this post: https://stackoverflow.com/a/707339/6244709
You will need to call the following;
filef.Close();
This would go before your delete;
while ((line = filef.ReadLine()) != null)
{
sb = new StringBuilder();
sb.AppendLine(line.Substring(0, line.Length));
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
folder = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName) + #"\Data\csv\done";
using (System.IO.StreamWriter files = new System.IO.StreamWriter(folder + #"\create-user-archive.csv", true))
{
files.WriteLine(",; " + sb.ToString().Split(';')[1] + ";" + sb.ToString().Split(';')[2] + ";" + sb.ToString().Split(';')[1] + "." + sb.ToString().Split(';')[2] + ";" + GenerateToken(6) + ";" + sb.ToString().Split(';')[3] + ";" + "1" + ";" + "1");
}
}
i++;
sourceFile = System.IO.Path.Combine(#"Data\csv\pending", file);
filef.Close();
File.Delete(sourceFile);
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
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'm having issues with a C# Winforms file IO. The code complies just fine, but then it returns errors on execution.
The output code is here:
private void saveData()
{
string fullPath = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
StreamWriter writer = new StreamWriter(fullPath + textBox2.Text + ".txt");
writer.WriteLine(textBox1.Text + "," + textBox2.Text + "," + textBox3.Text + "," + textBox4.Text + "," + comboBox1.SelectedText + "," +
numericUpDown25.Value + "," + numericUpDown1.Value + "," + numericUpDown2.Value + "," + numericUpDown3.Value + "," + numericUpDown4.Value + "," +
numericUpDown5.Value + "," + numericUpDown6.Value + "," + numericUpDown7.Value + "," + numericUpDown8.Value + "," + numericUpDown9.Value + "," +
numericUpDown10.Value + "," + numericUpDown11.Value + "," + numericUpDown12.Value + "," + numericUpDown13.Value + "," + numericUpDown14.Value
+ "," + numericUpDown15.Value + "," + numericUpDown16.Value + "," + numericUpDown17.Value + "," + numericUpDown18.Value + "," +
numericUpDown19.Value + "," + numericUpDown20.Value + "," + numericUpDown21.Value + "," + numericUpDown22.Value);
writer.Close();
}
And the code to load the data is here:
private void loadData()
{
Stream myStream = null;
OpenFileDialog openFileDialog1 = new OpenFileDialog();
openFileDialog1.InitialDirectory = System.Environment.GetEnvironmentVariable(#"%MyDocuments%\HellsingRPG\");
openFileDialog1.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
openFileDialog1.FilterIndex = 2;
openFileDialog1.RestoreDirectory = true;
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
try
{
if ((myStream = openFileDialog1.OpenFile()) != null)
{
using (myStream)
{
List<string> myData = parseCSV(System.Convert.ToString(myStream));
textBox1.Text = myData[0];
textBox2.Text = myData[1];
textBox3.Text = myData[3];
textBox4.Text = myData[4];
comboBox1.SelectedText = myData[5];
numericUpDown25.Value = System.Convert.ToDecimal(myData[6]);
numericUpDown1.Value = System.Convert.ToDecimal(myData[7]);
numericUpDown2.Value = System.Convert.ToDecimal(myData[8]);
numericUpDown3.Value = System.Convert.ToDecimal(myData[9]);
numericUpDown4.Value = System.Convert.ToDecimal(myData[10]);
numericUpDown5.Value = System.Convert.ToDecimal(myData[11]);
numericUpDown6.Value = System.Convert.ToDecimal(myData[12]);
numericUpDown7.Value = System.Convert.ToDecimal(myData[13]);
numericUpDown8.Value = System.Convert.ToDecimal(myData[14]);
numericUpDown9.Value = System.Convert.ToDecimal(myData[15]);
numericUpDown10.Value = System.Convert.ToDecimal(myData[16]);
numericUpDown11.Value = System.Convert.ToDecimal(myData[17]);
numericUpDown12.Value = System.Convert.ToDecimal(myData[18]);
numericUpDown13.Value = System.Convert.ToDecimal(myData[19]);
numericUpDown14.Value = System.Convert.ToDecimal(myData[20]);
numericUpDown15.Value = System.Convert.ToDecimal(myData[21]);
numericUpDown16.Value = System.Convert.ToDecimal(myData[22]);
numericUpDown17.Value = System.Convert.ToDecimal(myData[23]);
numericUpDown18.Value = System.Convert.ToDecimal(myData[24]);
numericUpDown19.Value = System.Convert.ToDecimal(myData[25]);
numericUpDown20.Value = System.Convert.ToDecimal(myData[26]);
numericUpDown21.Value = System.Convert.ToDecimal(myData[27]);
numericUpDown22.Value = System.Convert.ToDecimal(myData[28]);
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.Message);
}
}
}
And that compiles just fine. But when I use it, I get the following errors:
"Could not find file "C:\Users\collmark\Documents\Visual Studio
2015\Projects\WindowsFormsApplication1\WindowsFormsApplication1\bin\Release\System.IO.Filestream".
"Error: Could not read file from disk. Original error: Index out of
range. Must be non-negative and less than the size of the collection.
Parameter name: index."
Thanks
your save data seems to save 22 fields while the read expects 28.
I suspect the myData object does not contain the fields index you are trying to read, hence index out of range.
do yourself a favour when printing exception data don't limit yourself to the message but print the whole stack trace, it will tell you which line is faulty giving you a hint at the actual problem.
MessageBox.Show("Error: Could not read file from disk. Original error: " + ex.ToString());
I'm new in google analytic. I go through some regarding this. I found that there is no direct method to hit a windows application in google analytic. But i found some solutions in stackoverflow. I tried that, but didn't work for me. Below is the code that I'm using.
private void analyticsmethod4(string trackingId, string pagename)
{
Random rnd = new Random();
long timestampFirstRun, timestampLastRun, timestampCurrentRun, numberOfRuns;
// Get the first run time
timestampFirstRun = DateTime.Now.Ticks;
timestampLastRun = DateTime.Now.Ticks - 5;
timestampCurrentRun = 45;
numberOfRuns = 2;
// Some values we need
string domainHash = "123456789"; // This can be calcualted for your domain online
int uniqueVisitorId = rnd.Next(100000000, 999999999); // Random
string source = "Shop";
string medium = "medium123";
string sessionNumber = "1";
string campaignNumber = "1";
string culture = Thread.CurrentThread.CurrentCulture.Name;
string screenRes = Screen.PrimaryScreen.Bounds.Width + "x" + Screen.PrimaryScreen.Bounds.Height;
string statsRequest = "http://www.google-analytics.com/__utm.gif" +
"?utmwv=4.6.5" +
"&utmn=" + rnd.Next(100000000, 999999999) +
// "&utmhn=hostname.mydomain.com" +
"&utmcs=-" +
"&utmsr=" + screenRes +
"&utmsc=-" +
"&utmul=" + culture +
"&utmje=-" +
"&utmfl=-" +
"&utmdt=" + pagename + // Here i passed my profile name "MyWindowsApp"
"&utmhid=1943799692" +
"&utmr=0" +
"&utmp=" + pagename +
"&utmac=" + trackingId + //Tracking id : ie "UA-XXXXXXXX-X"
"&utmcc=" +
"__utma%3D" + domainHash + "." + uniqueVisitorId + "." + timestampFirstRun + "." + timestampLastRun + "." + timestampCurrentRun + "." + numberOfRuns +
"%3B%2B__utmz%3D" + domainHash + "." + timestampCurrentRun + "." + sessionNumber + "." + campaignNumber + ".utmcsr%3D" + source + "%7Cutmccn%3D(" + medium + ")%7Cutmcmd%3D" + medium + "%7Cutmcct%3D%2Fd31AaOM%3B";
try
{
using (var client = new WebClient())
{
//byte[] bt = client.DownloadData(statsRequest);
Stream data = client.OpenRead(statsRequest);
StreamReader reader = new StreamReader(data);
string s = reader.ReadToEnd();
MessageBox.Show(s);
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
This example is also got from this site itself. I don't know where was the problem. Please direct me, how can i make it. This is the output i'm getting "GIF89a".
Thanks
Bobbin Paulose
So it's working. The Google Analytics call loads a tiny GIF image, and the querystring parameters provided in the request trigger all the Google Analytics goodness. If you're getting a response back, you have registered your event successfully with Google.