I have a loop which scans for xml files, when success it get in to loop and manipulate strings. Problem is i can't write post because i got warning file in use. How do i fix this?
Loop:
var dir = new DirectoryInfo(#"C:\Projektdata");
foreach (var file in dir.EnumerateFiles("*.xml", SearchOption.AllDirectories))
{
foreach (string line in File.ReadLines(file.DirectoryName + #"\" + file))
{
. . . .
Section to write file:
string directoryPath = file.DirectoryName + #"\" + file;
StreamWriter writer = new StreamWriter(directoryPath);
writer.WriteLine(source);
writer.Close();
Use it in a using directive:
using(var writer = new StreamWriter(directoryPath))
{
writer.WriteLine(source);
}
If the error still occurs, try to save the string into a variable, and use this writing process outside of the scope of the foreach iterations. (Since the foreach iteration reads the file line by line, so it means the file is open.)
You can't write to an open file. You already opened the same file for reading.
File.ReadLines(file.DirectoryName + #"\" + file);
and
string directoryPath = file.DirectoryName + #"\" + file;
StreamWriter writer = new StreamWriter(directoryPath);
File.ReadLines() is returning an IEnumerable<string> and will yield each line. So within the loop, the file is still open. Assumed that the writing is within the loop.
Related
I want rewrite my txt file(I need delete lines). I use this code:
string cesta3 = cesta + "database.txt";
string file = new StreamReader(cesta3).ReadToEnd();
var linesToKeep = File.ReadLines(cesta3)
.Where(l => l != "Meno: " + textBox1.Text + " PN " + textBox2.Text);
But I don't know how to save my file with that same name.I try this:
File.WriteAllLines(cesta3, linesToKeep); // <== exception
var tempFile = Path.GetTempFileName();
File.Move(tempFile + ".txt", cesta3);
But it throws exception:
Additional information: Access to the path "'C:\Users\Lenovo\documents\visual studio 2015\Projects\attendancer\attendancer\bin\Debug\database.txt' is denied."
How can I do ?
This line of code locks the file and prevent it from moving: string file = new StreamReader(cesta3).ReadToEnd();.
Fix:
you can properly close StreamReader after reading file text from it with using
alternatively since there is nothing in the sample using that StreamReader or result of ReadToEnd (file variable) you can simply remove that line.
Side note: File.Move will throw more exceptions after you are done with the first one as source file is unlikely to exist - I'm not sure what you were trying to do with that call.
In this method, I saved an excel file in a directory in that path, instead of writing the whole path, is there a way to make it short so it automatically saves in the debug file?
using (var file = File.Open("C:\\Users\\john\\Documents\\Visual Studio 2015\\Projects\\EXCEl PROJECT\\webform\\" + filename + ".xlsx",FileMode.Create))
{
ms.WriteTo(file); // copy the memory stream to the file stream
}
Use this property as your base directory. You may append to it as needed.
System.AppDomain.CurrentDomain.BaseDirectory
Sample:
using (var file = File.Open(AppDomain.CurrentDomain.BaseDirectory + "\\webform\\" + filename + ".xlsx", FileMode.Create))
{
ms.WriteTo(file); // copy the memory stream to the file stream
}
I am creating a text file and after that I am trying to write some text in that file.but when writing text,it's generating exception that process cannot access file because it's being used by another process. Kindly someone help :( Thanks in advance.
Here is my code
dt_Loc = loc1_ctab.GetEmpLocInfo(Session["empcd"].ToString());
string str = DateTime.Now.ToString("dd-mmm-yyyy");
str = dt_Loc.Rows[0]["loc1_abrv"].ToString() + "-" + str;
string path = FilesPath.Path_SaveFile + str + ".txt";
if (!File.Exists(path))
{
File.Create(path);
TextWriter tw = new StreamWriter(path);
tw.WriteLine(txt_comments.Text);
tw.Close();
}
Remove the File.Create since it opens a FileStream for the file.This results in the file being open and hence you get the exception that the file is being used by another process.
if (!File.Exists(path))
{
using(StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine(txt_comments.Text);
}
}
Your code giving such error because, the method Create Creates or overwrites a file in the specified path. which will return A FileStream that provides read/write access to the file specified in path. So at the time of executing the writemethod, the file is being used by the returned FS. you can use this in the following way:
using (FileStream fs = File.Create(path))
{
Byte[] info = new UTF8Encoding(true).GetBytes(txt_comments.Text);
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
You can Make it simple by using File.WriteAllText which will Creates a new file, write the contents to the file, and then closes the file. If the target file already exists, it is overwritten.
string path =FilesPath.Path_SaveFile + str + ".txt";;
if (!File.Exists(path))
{
File.WriteAllText(path, txt_comments.Text);
}
i wrote this code , it ctreates folder named "Fitness50" each time but the text file is not created.i want to create textfile within this folder and then save values of an arraylist.
so for i have tried this
DirectoryInfo myDir = new DirectoryInfo(#"E:");
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
myDir = new DirectoryInfo(ParentFolderName1);
ParentFolderName1 = "Fittness50";
myDir.CreateSubdirectory(ParentFolderName1);
FileName1 = "./" + "" + ParentFolderName1 + "" + "/" + "Fittness10" + "" + "" + PopulationID + "" + ".txt";
FileStream fs2 = new FileStream(FileName1, FileMode.Create, FileAccess.Write);
StreamWriter SW2 = new StreamWriter(fs2);
for (i = 0; i < AlTargetData.Count; i++)
{
SW2.WriteLine(AlTargetData[i]);
}
AlTargetData.Clear();
SW2.Close();
fs2.Close();
Well, first of all, / is not the preferred directory separator on Windows, but \ is. Just because / happens to work, there's no reason to use it. Secondly, you're not creating the Fittness10 folder at all, but you're creating Fittness50 twice. And third, you're not writing the file to the folders you create, but to the current working directory ..
Your code (or at least what I understand you want to achieve) can be shortened significantly to this:
string path = #"E:\Fittness50\Fittness10";
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
string fileName = Path.Combine(path, String.Format("{0}.txt", PopulationID));
File.WriteAllText(fileName, String.Join(Environment.NewLine, AlTargetData));
Please note that you should not consider writing to bin\debug. There will be no bin\debug on the end-user's machine. If the user installs your application, it will be most probably be installed in the Program Files folder, which your application won't be allowed to write to. Instead, consider writing to a common location, like the ones you can chose from in Environment.GetFolderPath.
At first run, my program, writes to a csv file in the first line,
But, when I'm running my program at the second.. third.. time, it runs over the first line..
how can i correct it?
I would like to have a CSV file input of all the entering to my program.
The code is as follows:
private void WriteToCsvFile()
{
var us = users.ElementAt(0);
string names = "Number',";
string userAnswer = (us.userName + ",");
foreach (string ss in user)
{
string str = Path.GetFileName(ss);
names = names + str + ",";
}
foreach (string ans in us.answer)
{
userAnswer = userAnswer + ans + ",";
}
using (StreamWriter sw = new StreamWriter("EntranceLog.csv"))
{
sw.WriteLine(names);
sw.WriteLine(userAnswer);
}
this.Close();
}
Add true parameter in the constructor:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
The second parameter named append controls whether an existing file shall be overwritten or appended. MSDN states:
true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.
Each time it is run, you are creating a new file with the same name is overwriting the older file. That is the default behavior of the specific constructor you are using.
You want to use this constructor instead and specify the append parameters as true:
using (StreamWriter sw = new StreamWriter("EntranceLog.csv", true))
{
// write your file as normal
}