I have a problem that is:
I have a program that writes on a file throw File.WriteAllText, and it works fine until I close the activity in which it writes. When I close that activity, the file hasn't saved the changes I've made.
What might be the problem?
var path = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
var filename = Path.Combine(path, "Produtos.txt");
atual = File.ReadAllText (filename);
novo = atual + System.Environment.NewLine + _nome + ";" + _preco + ";" + _unidade + ";" + _categoria;
File.WriteAllText (filename, novo);
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 ;)
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);
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.
I use a file upload control to save a CSV file into server. CSV File having a column deviceid.It has the 17 digit number like '12345678901234567' but treated as a string. Now i am using the below code to save this csv in server.
Now i open the same file from server but the same column format changed from string to number with exponential format and the last two digit treated as 0. How can i store the csv without changing datatype.
string rnd_number = Convert.ToString(random.Next(1, 100000));
path = System.IO.Path.GetFileName(fp_excel.PostedFile.FileName);
SaveLocation = Server.MapPath("Document" + "\\" + folder.Trim() + "\\" + rnd_number + fileExt);
path = "../Document/" + folder + "/" + rnd_number + fileExt;
ViewState["path"] = Server.MapPath(#"Document/" + folder + "/" + rnd_number + fileExt);
fp_excel.PostedFile.SaveAs(SaveLocation);
lbl_msg.Text = path;
update(Server.MapPath(#"Document/" + folder + "/" + rnd_number + fileExt));
Can you try format number to string like below
Dim style As String = "<style>.textmode{mso-number-format:\#;}</style>"
Refer : http://www.aspsnippets.com/Articles/Export-GridView-To-Word-Excel-PDF-CSV-Formats-in-ASP.Net.aspx
I have an application that reads a delimited file using ODBC. The connection string is as follows:
cs = #"Driver={Microsoft Text Driver (*.txt; *.csv)};DBQ=" + sPath1;
One of the companies providing a file is not using a header row, and I'm losing the first row of data. Putting HDR=No in the connection string does not seem to help. There is a schema.ini in the target directory.
cs = #"Driver={Microsoft Text Driver (*.txt; *.csv)};HDR=No;DBQ=" + sPath1;
What's the best way to read the first row? I haven't tried the Excel driver because I'm afraid it will interpret data differently.
The solution is to be sure there is a line reading
ColNameHeader=False
in the schema.ini. Documentation can be found here:
http://msdn.microsoft.com/en-us/library/ms709353%28VS.85%29.aspx
To follow up on the correct answer, you can also write a function to create/write your schema file as a FileStream at run time. Include ColNameHeader=False (or pass it as a parameter) when you write to the file. The file name must be schema.ini
private void writeSchema(string decimalPointOverride = "", string header="True")
{
try
{
FileStream fsOutput = new FileStream( myDirectory + "\\schema.ini", FileMode.Create, FileAccess.Write);
StreamWriter srOutput = new StreamWriter(fsOutput);
string s1, s2, s3, s4, s5, s6;
s1 = "[" + "OutputFileName.CSV" + "]";
s2 = "ColNameHeader=" + header;
s3 = "Format=" + this.strFormat;
s4 = "MaxScanRows=25";
s5 = "CharacterSet=" + this.strEncoding;
//set decimal point if exists, otherwise put empty string ""
s6 = (decimalPointOverride == "") ? "" : "DecimalSymbol=" + decimalPointOverride + "\r\n";
srOutput.WriteLine(s1.ToString() + "\r\n" + s2.ToString() + "\r\n" + s3.ToString() + "\r\n" + s4.ToString() + "\r\n" + s5.ToString() + "\r\n" + s6.ToString());
srOutput.Close();
fsOutput.Close();
}
catch (Exception ex)
{
Console.WriteLine(ex.Message, "writeSchema");
}
}