C# "The process cannot access the file because it is being used by another process" error - c#

I've been trying to figure out what's my error here for a few minutes now. can someone help?
public void UpdateItemList(string word, string replacement)
{
StreamReader reader = new StreamReader("items.txt");
string input = reader.ReadToEnd();
using (StreamWriter writer = new StreamWriter("items.txt", true))
{
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
writer.Close();
}
reader.Close();
}
I added reader.Close() and writer.Close() and gave different orientation, I'm not sure what I'm missing.

you should close StreamReader before opening streamWriter
public void UpdateItemList(string word, string replacement)
{
string input;
using (StreamReader reader = new StreamReader("items.txt"))
{
input = reader.ReadToEnd();
}
using (StreamWriter writer = new StreamWriter("items.txt", false))
{
string output = input.Replace(word, replacement);
writer.Write(output);
}
}

Related

Return byte array of openxml document

I'm using the following code to generate an openxml document and save it on the server and that works fine, however now i'm trying to generate it to a byte stream to serve out straight away without saving to the server but the document gets corrupted in the process.
Working Code
public static void CreateWordDoc(List<objReplace> lstReplace, String TemplateFile, String OutputPath)
{
File.Delete(OutputPath);
File.Copy(TemplateFile, OutputPath);
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(OutputPath, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
docText = sr.ReadToEnd();
foreach (var ro in lstReplace)
{
Regex regexText = new Regex(ro.Find);
docText = regexText.Replace(docText, ro.Replace);
}
using (StreamWriter sw = new StreamWriter(wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
}
}
}
Code that produces currupted XML - that I want to get working
public static byte[] CreateWordDocToStream(List<objReplace> lstReplace, String TemplateFile)
{
string docText = null;
byte[] filebytes = File.ReadAllBytes(TemplateFile);
using (MemoryStream stream = new MemoryStream(filebytes))
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
{
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
docText = sr.ReadToEnd();
foreach (var ro in lstReplace)
{
Regex regexText = new Regex(ro.Find);
docText = regexText.Replace(docText, ro.Replace);
}
}
}
return Encoding.ASCII.GetBytes(docText);
}

c# exception file is being used by another process

i have trouble with the following two functions. Both have a indentical basic scheme but first one work, second one causes an exception at marked line("File is used by another process").
// this works
public static void EncryptFile(string FileName)
{
string ToEncrypt = null;
using(StreamReader sr = new StreamReader(FileName))
{
ToEncrypt = sr.ReadToEnd();
}
using(StreamWriter sw = new StreamWriter(FileName, false))
{
string Encrypted = Encrypt(ToEncrypt, true);
sw.Write(Encrypted);
}
}
// this works not - see commented lin
public static void DecryptFile(string FileName)
{
string ToDecrypt = null;
using (StreamReader sr = new StreamReader(FileName))
{
ToDecrypt = sr.ReadToEnd();
}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
I have tried with an additional Close() after read and write, but this works not too.
I hope, somebody can help.
Thanks
Torsten
Is the function called from multiple threads? If yes you may want to declare a static object on class level and place a lock statement around the entire body of that method. Like this:
private static Object syncObject = new Object()
// this works not - see commented lin
public static void DecryptFile(string FileName)
{
lock(syncObject)
{
string ToDecrypt = null;
using (StreamReader sr = new StreamReader(FileName))
{
ToDecrypt = sr.ReadToEnd();
}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
}
Also could you, just for fun, comment the StreamReader statement and try to run the method again? If it still doesn't work, check if you've that file open in a texteditor or something alike by using ProcessExplorer or something similiar.
edit
could you comment the StreamReader part? So that it looks like this:
public static void DecryptFile(string FileName)
{
//string ToDecrypt = null;
//using (StreamReader sr = new StreamReader(FileName))
//{
// ToDecrypt = sr.ReadToEnd();
//}
// here comes the exception
using (StreamWriter sw = new StreamWriter(FileName, false))
{
string Decrypted = Decrypt(ToDecrypt, true);
sw.Write(Decrypted);
}
}
also could you try to open an exclusive FileStream on that file before the StreamReader and once after the StreamReader but before the StreamWriter? http://msdn.microsoft.com/de-de/library/tyhc0kft%28v=vs.110%29.aspx
Also could you try and use another file for that method?

WIndows Phone 7 reading file to String

I'm trying to read a file entirely to a String variable.
I did this:
String text;
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var readStream = new IsolatedStorageFileStream("k.dat", FileMode.Open, store))
using (var reader = new StreamReader(readStream))
{
text= reader.ReadToEnd();
}
textBlock1.Text = text;`
It gave me a "Operation not permitted on IsolatedStorageFileStream" message from an IsolatedStorageException.
What am I doing wrong?
I tried by adding a .txt and .xml file in the file name, but it didn't work.
Where am I to put the file anyway? I tried
~\Visual Studio 2010\Projects\Parsing\Parsing\k.dat
I'm parsing it later using:
XmlReader reader = XmlReader.Create(new StringReader(xmldata));
flagLink = false;
while (reader.Read())
{
//and so on
Try with..
string text;
string filename="k.txt";
using (IsolatedStorageFile isolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
if (isolatedStorage.FileExists(fileName))
{
StreamReader reader = new StreamReader(new IsolatedStorageFileStream(fileName, FileMode.Open, isolatedStorage));
text = reader.ReadToEnd();
reader.Close();
}
if(!String.IsNullOrEmpty(text))
{
MessageBox.Show(text);
}
}
EDIT:
In case of xml,
try
{
using (IsolatedStorageFile myIsolatedStorage = IsolatedStorageFile.GetUserStoreForApplication())
{
IsolatedStorageFileStream isoFileStream = myIsolatedStorage.OpenFile("test.xml", FileMode.Open); //you can use your filename just like above code
using (StreamReader reader = new StreamReader(isoFileStream))
{
this.textbox1.Text = reader.ReadToEnd();
}
}
}
catch
{ }
This is the entire method and this worked fully:
String sFile = "k.dat";
IsolatedStorageFile myFile = IsolatedStorageFile.GetUserStoreForApplication();
//myFile.DeleteFile(sFile);
if (!myFile.FileExists(sFile))
{
IsolatedStorageFileStream dataFile = myFile.CreateFile(sFile);
dataFile.Close();
}
var resource = Application.GetResourceStream(new Uri(#"k.dat", UriKind.Relative));
StreamReader streamReader = new StreamReader(resource.Stream);
string rawData = streamReader.ReadToEnd();
return rawData;

Create File If File Does Not Exist

I need to get my code to read if file doesnt exist create else append. Right now it is reading if it does exist create and append. Here is the code:
if (File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Would I do this?
if (! File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
Edit:
string path = txtFilePath.Text;
if (!File.Exists(path))
{
using (StreamWriter sw = File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
}
else
{
StreamWriter sw = File.AppendText(path);
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
sw.Close();
}
}
You can simply call
using (StreamWriter w = File.AppendText("log.txt"))
It will create the file if it doesn't exist and open the file for appending.
Edit:
This is sufficient:
string path = txtFilePath.Text;
using(StreamWriter sw = File.AppendText(path))
{
foreach (var line in employeeList.Items)
{
Employee e = (Employee)line; // unbox once
sw.WriteLine(e.FirstName);
sw.WriteLine(e.LastName);
sw.WriteLine(e.JobTitle);
}
}
But if you insist on checking first, you can do something like this, but I don't see the point.
string path = txtFilePath.Text;
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{
foreach (var line in employeeList.Items)
{
sw.WriteLine(((Employee)line).FirstName);
sw.WriteLine(((Employee)line).LastName);
sw.WriteLine(((Employee)line).JobTitle);
}
}
Also, one thing to point out with your code is that you're doing a lot of unnecessary unboxing. If you have to use a plain (non-generic) collection like ArrayList, then unbox the object once and use the reference.
However, I perfer to use List<> for my collections:
public class EmployeeList : List<Employee>
or:
using FileStream fileStream = File.Open(path, FileMode.Append);
using StreamWriter file = new StreamWriter(fileStream);
// ...
You don't even need to do the check manually, File.Open does it for you. Try:
using (StreamWriter sw = new StreamWriter(File.Open(path, System.IO.FileMode.Append)))
{
Ref: http://msdn.microsoft.com/en-us/library/system.io.filemode.aspx
2021
Just use File.AppendAllText, which creates the file if it does not exist:
File.AppendAllText("myFile.txt", "some text");
Yes, you need to negate File.Exists(path) if you want to check if the file doesn't exist.
This works as well for me
string path = TextFile + ".txt";
if (!File.Exists(HttpContext.Current.Server.MapPath(path)))
{
File.Create(HttpContext.Current.Server.MapPath(path)).Close();
}
using (StreamWriter w = File.AppendText(HttpContext.Current.Server.MapPath(path)))
{
w.WriteLine("{0}", "Hello World");
w.Flush();
w.Close();
}
This will enable appending to file using StreamWriter
using (StreamWriter stream = new StreamWriter("YourFilePath", true)) {...}
This is default mode, not append to file and create a new file.
using (StreamWriter stream = new StreamWriter("YourFilePath", false)){...}
or
using (StreamWriter stream = new StreamWriter("YourFilePath")){...}
Anyhow if you want to check if the file exists and then do other things,you can use
using (StreamWriter sw = (File.Exists(path)) ? File.AppendText(path) : File.CreateText(path))
{...}
For Example
string rootPath = Path.GetPathRoot(Environment.GetFolderPath(Environment.SpecialFolder.System));
rootPath += "MTN";
if (!(File.Exists(rootPath)))
{
File.CreateText(rootPath);
}
private List<Url> AddURLToFile(Urls urls, Url url)
{
string filePath = #"D:\test\file.json";
urls.UrlList.Add(url);
//if (!System.IO.File.Exists(filePath))
// using (System.IO.File.Delete(filePath));
System.IO.File.WriteAllText(filePath, JsonConvert.SerializeObject(urls.UrlList));
//using (StreamWriter sw = (System.IO.File.Exists(filePath)) ? System.IO.File.AppendText(filePath) : System.IO.File.CreateText(filePath))
//{
// sw.WriteLine(JsonConvert.SerializeObject(urls.UrlList));
//}
return urls.UrlList;
}
private List<Url> ReadURLToFile()
{
// string filePath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), #"App_Data\file.json");
string filePath = #"D:\test\file.json";
List<Url> result = new List<Url>(); ;
if (!System.IO.File.Exists(filePath))
using (System.IO.File.CreateText(filePath)) ;
using (StreamReader file = new StreamReader(filePath))
{
result = JsonConvert.DeserializeObject<List<Url>>(file.ReadToEnd());
file.Close();
}
if (result == null)
result = new List<Url>();
return result;
}

c# edit txt file without creating another file (without StreamWriter)

Because I'm using non-latin alphabet, if I use StreamWriter, the characters aren't correct.
String line;
StreamReader sr = new StreamReader(#"C:\Users\John\Desktop\result.html");
line = sr.ReadLine();
while (line != null)
{
line = sr.ReadLine();
if (line.Contains("</head>"))
{
line = "<img src=\"result_files\\image003.png\"/>" + line;
}
}
sr.Close();
Here I'm editing the string I want to edit in the file, but I'm not saving it in the same file. How to do that?
If you use one of the StreamWriter constructors that accepts an encoding you shouldn't have any problems with incorrect characters. You are also skipping the first line in your reading method.
Encoding encoding;
StringBuilder output = new StringBuilder();
using (StreamReader sr = new StreamReader(filename))
{
string line;
encoding = sr.CurrentEncoding;
while ((line = sr.ReadLine()) != null)
{
if (line.Contains("</head>"))
{
line = "<img src=\"result_files\\image003.png\"/>" + line;
}
output.AppendLine(line);
}
}
using (StreamWriter writer = new StreamWriter(filename, false, encoding))
{
writer.Write(output.ToString());
}
I think the easiest approach would be
open the file in read/write mode
read everything from the file
make the modifications inmemory
rewrite it back to the file rather than appending..
you use a StreamReader. And the name say what it's function. To read!
Dirty-Code
if (File.Exists(fileName))
{
int counter = 1;
StringBuilder sb = new StringBuilder();
foreach (string s in File.ReadAllLines(fileName, Encoding.Default))
{
if (s.Contains("</head>"))
{
s= "<img src=\"result_files\\image003.png\"/>" + line;
}
sb.AppendLine(s);
counter++;
}
File.WriteAllText(fileName, sb.ToString(), Encoding.Default);
}

Categories

Resources