Im trying to use using but getting error on the using it self.
public void Save(string path , bool Locked , PictureBox pb)
{
string fn;
string t = Path.GetFileNameWithoutExtension(wo_name);
if (File.Exists(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name))
{
using (string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name))
{
File.Delete(f);
}
fn = path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name;
}
else
{
fn = path + "\\" + "DATABASE" + "\\" + wo_name + "\\" + wo_name + ".txt";
}
OptionsFile setting_file = new OptionsFile(fn);
setting_file.SetKey("File Name", fn);
setting_file.SetKey("Version", version);
setting_file.SetKey("Button Lock", Locked.ToString());
setting_file.SetKey("picturebox.Width", pb.Width.ToString());
setting_file.SetKey("picturebox.Height", pb.Height.ToString());
setting_file.SetListFloatKey("Coordinates_X", woc.Point_X);
setting_file.SetListFloatKey("Coordinates_Y", woc.Point_Y);
setting_file.SetListIntKey("ConnectionStart", connectionStart);
setting_file.SetListIntKey("ConnectionEnd", connectionEnd);
}
In this save function above i did:
using (string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name))
{
File.Delete(f);
}
Before it there was just string f = ....Path.... and the Fiel.Delete
I just added the using but on the using im getting error: 'string': type used in a using statement must be implicitly convertible to 'System.IDisposable'
Is there a Close or Dispose method on the OptionsFile class? Before you exit the Save and Load functions you should make sure to call one or the other. If you don't, then you'll likely have to wait until the setting_file instance is garbage collected before the lock on the file is released. If you don't allocate a lot of memory, that could take awhile!
If OptionsFile.Dispose exists then enclose your use of OptionsFile in a using statement, which will call Dispose automatically for you at the end of the statement, even if an exception is thrown.
public void Save(string path , bool Locked , PictureBox pb)
{
string fn;
string t = Path.GetFileNameWithoutExtension(wo_name);
if (File.Exists(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name))
{
string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name);
File.Delete(f);
fn = path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name;
}
else
{
fn = path + "\\" + "DATABASE" + "\\" + wo_name + "\\" + wo_name + ".txt";
}
using (OptionsFile setting_file = new OptionsFile(fn))
{
setting_file.SetKey("File Name", fn);
setting_file.SetKey("Version", version);
setting_file.SetKey("Button Lock", Locked.ToString());
setting_file.SetKey("picturebox.Width", pb.Width.ToString());
setting_file.SetKey("picturebox.Height", pb.Height.ToString());
setting_file.SetListFloatKey("Coordinates_X", woc.Point_X);
setting_file.SetListFloatKey("Coordinates_Y", woc.Point_Y);
setting_file.SetListIntKey("ConnectionStart", connectionStart);
setting_file.SetListIntKey("ConnectionEnd", connectionEnd);
}
}
public void Load( string path)
{
string fn = path + "\\" + wo_name;
using (OptionsFile setting_file = new OptionsFile(fn))
{
woc.Point_X = new List<float>();
woc.Point_Y = new List<float>();
woc.Point_X = setting_file.GetListFloatKey("Coordinates_X");
woc.Point_Y = setting_file.GetListFloatKey("Coordinates_Y");
connectionStart = new List<int>();
connectionEnd = new List<int>();
connectionStart = setting_file.GetListIntKey("ConnectionStart");
connectionEnd = setting_file.GetListIntKey("ConnectionEnd");
lockObject = setting_file.GetKey("Button Lock");
}
}
If OptionsFile.Close exists then enclose your use of OptionsFile in a try/finally block, so you can ensure Close is called even if an exception is thrown.
public void Save(string path , bool Locked , PictureBox pb)
{
string fn;
string t = Path.GetFileNameWithoutExtension(wo_name);
if (File.Exists(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name))
{
string f = Path.Combine(path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name);
File.Delete(f);
fn = path + "\\" + "DATABASE" + "\\" + t + "\\" + wo_name;
}
else
{
fn = path + "\\" + "DATABASE" + "\\" + wo_name + "\\" + wo_name + ".txt";
}
OptionsFile setting_file = null;
try
{
setting_file = new OptionsFile(fn);
setting_file.SetKey("File Name", fn);
setting_file.SetKey("Version", version);
setting_file.SetKey("Button Lock", Locked.ToString());
setting_file.SetKey("picturebox.Width", pb.Width.ToString());
setting_file.SetKey("picturebox.Height", pb.Height.ToString());
setting_file.SetListFloatKey("Coordinates_X", woc.Point_X);
setting_file.SetListFloatKey("Coordinates_Y", woc.Point_Y);
setting_file.SetListIntKey("ConnectionStart", connectionStart);
setting_file.SetListIntKey("ConnectionEnd", connectionEnd);
}
finally
{
if (setting_file != null)
setting_file.Close();
}
}
public void Load( string path)
{
string fn = path + "\\" + wo_name;
OptionsFile setting_file = null;
try
{
setting_file = new OptionsFile(fn);
woc.Point_X = new List<float>();
woc.Point_Y = new List<float>();
woc.Point_X = setting_file.GetListFloatKey("Coordinates_X");
woc.Point_Y = setting_file.GetListFloatKey("Coordinates_Y");
connectionStart = new List<int>();
connectionEnd = new List<int>();
connectionStart = setting_file.GetListIntKey("ConnectionStart");
connectionEnd = setting_file.GetListIntKey("ConnectionEnd");
lockObject = setting_file.GetKey("Button Lock");
}
finally
{
if (setting_file != null)
setting_file.Close();
}
}
If you don't have a Dispose or a Close method, then you need to modify your OptionsFile class to implement IDisposable or have a Close method, where you in turn close or dispose of any Stream based instances.
Related
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 ;)
In a WinForms project I am trying to extract archive in destination folder, but I not want to extract the folder from archive in destination folder.
I want to extract only the file.
My code:
private void button1_Click(object sender, EventArgs e)
{
string Info = "";
string extractPath = #"D:\dosfiles\SYNOPD\SYNOPD$$.PD\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\";
string zipPath = #"D:\dosfiles\" + comboBox1.SelectedItem.ToString() + "_" + comboBox2.SelectedItem.ToString() + "_" + comboBox3.SelectedItem.ToString() + "S" + ".zip";
if (!Directory.Exists(extractPath))
{
Info += "Folder not exists in D:\\dosfiles\\SYNOPD\\SYNOPD$$.PD\\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + comboBox1.SelectedItem.ToString();
}
else if(Directory.Exists(extractPath))
{
if (Directory.Exists(extractPath))
{
Directory.Delete(extractPath, true);
}
ZipFile.ExtractToDirectory(zipPath, extractPath);
Info += "Your synoptic files has been extracted in D:\\dosfiles\\SYNOPD\\SYNOPD$$.PD\\" + comboBox3.SelectedItem.ToString() + #"\" + comboBox2.SelectedItem.ToString() + #"\" + comboBox1.SelectedItem.ToString() + Environment.NewLine;
}
if (Info != "")
{
MessageBox.Show(Info);
Application.Exit();
}
}
}
}
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 have Troubles to write more than one time on the txt-file. First time it works fine but even if i try the GetFileAsynchronous-Method the File is just overwritten. How do I solve this Problem?
public async void write(string errormessage)
{
StorageFolder externalDevices = KnownFolders.RemovableDevices;
IReadOnlyList<StorageFolder> externalDrives = await externalDevices.GetFoldersAsync();
if (externalDrives.Count > 0)
{
StorageFolder removalableDrive = externalDrives[3];
String filename = "log_" + DateTime.UtcNow.Date.Day
+ "_" + DateTime.UtcNow.Date.Month + "_" + DateTime.UtcNow.Date.Year
+ "-" + DateTime.UtcNow.TimeOfDay.Hours
+ "_" + DateTime.UtcNow.TimeOfDay.Minutes + "_"
+ DateTime.UtcNow.TimeOfDay.Seconds + ".txt";
StorageFile file = await removalableDrive.CreateFileAsync(filename);
Stream w = await file.OpenStreamForWriteAsync();
StreamWriter sw = new StreamWriter(w);
sw.WriteLine("\n" + DateTime.UtcNow.TimeOfDay.Hours + ":" + DateTime.UtcNow.TimeOfDay.Minutes + ":" + DateTime.UtcNow.TimeOfDay.Seconds + ": " + errormessage);
sw.Dispose();
}
}
Thank you for your help.