Creating the same bin file as content of string C# - c#

I would like to create a bin file for example file.bin with the same content as a string variable contains. For example I have string str="10101" and I want to create conversion of str's content to bin file. After conversion, when I open file.bin I want to see the same content as str: 10101. I tried to do that by this way:
string path = "files/file.bin";
string str = "10101";
File.Create(path);
BinaryWriter bwStream = new BinaryWriter(new FileStream(path, FileMode.Create));
BinaryWriter binWriter = new BinaryWriter(File.Open(path, FileMode.Create));
for (int i = 0; i < str.Length; i++)
{
binWriter.Write(str[i]);
}
binWriter.Close();
but i get exception like
"System.IO.IOException: The process can not access the file
"C:\path.."
because it is being used by another process.. and few more exception.

The path/file you are trying to access is used by some other application. Close all the application which can/has opened the file,file.bin, which you are creating and then the code. It should work. You can remove bwStream variable line, if no other application is running.

You get the error because you are opening the file twice. The second time fails because the file is already open.
To write the string to the file you can just use the File.WriteAllText method:
string path = "files/file.bin";
string str = "10101";
File.WriteAllText(path, str);
Note: The string is encoded as utf-8 when it is written to the file.

File.Create() uses the file, try:
File.Create(path).Dispose();
BinaryWriter bwStream = new BinaryWriter(File.Open(path, FileMode.Append, FileAccess.Write, FileShare.ReadWrite));

Related

I'm getting "The process cannot access the file because it is being used by another process" error. Any ideas?

So, I created a file and a txt file into the AppData, and I want to overwrite the txt. But when I try to do it, it keeps giving me that error. Any ideas?
string path = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
string setuppath = (path + "\\");
string nsetuppath = (setuppath + "newx" + "\\");
Directory.CreateDirectory(nsetuppath);
string hedef2 = (nsetuppath + "commands.txt");
File.Create(hedef2);
StreamWriter sw = new StreamWriter(hedef2); ----> This is where the error appears.
sw.WriteLine("Testtest");
Just use the using statement when using streams. The using statement automatically calls Dispose on the object when the code that is using it has completed.
//path to the file you want to create
string path = #"C:\code\Test.txt";
// Create the file, or overwrite if the file exists.
using (FileStream fs = File.Create(path))
{
byte[] info = new UTF8Encoding(true).GetBytes("This is some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
There are many ways of manipulate streams, keep it simple depending on your needs

how to clear text file content c#

i want clear text file contet with this method
private void writeTextFile(string filePath, string text)
{
if (!File.Exists(filePath))
{
File.Create(filePath).Close();
}
using (StreamWriter tw = new StreamWriter(filePath))
{
File.WriteAllText(filePath,"");
tw.WriteLine(text);
tw.Close();
}
}
but i get this error
The process cannot access the file because it is being used by another process.
but this not open in anywhere ,
please help me
thank's
That's because you're creating a StreamWriter, then using File.WriteAllText. Your File is already being accessed with the StreamWriter.
File.WriteAllText does just that, writes the entire string you pass to it to a file. StreamWriter is unnecessary if you're going to use File.WriterAllText.
If you don't care about overwriting an existing file, you can do this:
private void writeTextFile(string filePath, string text)
{
File.WriteAllText(filePath, text);
}
If you want to use StreamWriter (which, by the way, File.WriteAllText uses, it just hides it), and append to the file, you can do this (from this answer):
using(StreamWriter sw = File.AppendText(path))
{
tw.WriteLine(text);
}
You can use StreamWriter for creating a file for write and use Truncate to write with clearing previous content.
StreamWriter writeFile;
writeFile = new StreamWriter(new IsolatedStorageFileStream(filename, FileMode.Truncate, myIsolatedStorage));
writeFile.WriteLine("String");
writeFile.Close();
This use FileMode.Truncate
Truncate Specifies that an existing file it to be opened and then truncated so that its size is zero bytes.
Assuming that your file already exists and you want to clear its contents before populating it or whatever, I found the best way to do this with StreamWriter is..
// this line does not create test.txt file, assuming that it already exists, it will remove the contents of test.txt
Dim sw As System.IO.StreamWriter = New System.IO.StreamWriter(Path.GetFullPath(C:\test.txt), False)
// this line will now be inserted into your test.txt file
sw.Write("hey there!")
// I decided to use this solution
// this section is to clear MyFile.txt
using(StreamWriter sw = new StreamWriter(#"MyPath\MyFile.txt", false))
{
foreach(string line in listofnames)
{
sw.Write(""); // change WriteLine with Write
}
sw.Close();
}
// and this section is to copy file names to MyFile.txt
using(StreamWriter file = new StreamWriter(#"MyPath\MyFile.txt", true))
{
foreach(string line in listofnames)
{
file.WriteLine(line);
}
}
You only need to specify false in the second parameter of the constructor for StreamWriter( route, false )
String ruta = #"C:\Address\YourFile".txt";
using (StreamWriter file = new StreamWriter(ruta, false))
{
for ( int i = 0; i < settings.Length; ++i )
file.WriteLine( settings[ i ] );
file.Close();
}
The problem is with you locking the file by initializing StreamWriter onto filePath and then trying to call File.WriteAllText which also internally attempts to lock the file and eventually end up with an exception being thrown.
Also from what it looks you are trying to clear the file's content and then write something in.
Consider the following:
private void writeTextFile(string filePath, string text) {
using (StreamWriter tw = new StreamWriter(filePath, false)) //second parameter is `Append` and false means override content
tw.WriteLine(text);
}
Why not use FileStream with FileMode.Create?
using (var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
//Do something...
}
Look at the MSDN of FileMode Enum
Create
Specifies that the operating system should create a new file. If the file already exists, it will be overwritten. This requires Write permission. FileMode.Create is equivalent to requesting that if the file does not exist, use CreateNew; otherwise, use Truncate. If the file already exists but is a hidden file, an UnauthorizedAccessException exception is thrown.
Overwritten will cover/remove/clean/delete all existed file data.
if you would like to use StreamWriter, use new StreamWriter(fs).

The process cannot access the file 'D:.txt' because it is being used by another process in c#

I have a pdf file which i am trying to read and write into text file in c# using itext.Now i have created a text file and trying to write my pdf values into it but it is giving following error..
The process cannot access the file 'D:\9008028901.txt' because it is being used by another process.
Here is my code in c#..
public bool ExtractText(string inFileName, string outFileName)
{
StreamWriter outFile = null;
try
{
// Create a reader for the given PDF file
PdfReader reader = new PdfReader(inFileName);
outFile = File.CreateText(outFileName);
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);
Here in my code text file is getting created but i ma not able to write any thing in it.My text file is blank.
Please help me..
The File.CreateText method returns a StreamWriter object that is holding the file open. This is not closed and then you try to open the file again with the new StreamWriter call and hence run into the file in use error. To fix this you need to close the first StreamWriter
outFile = File.CreateText(outFileName);
outFile.Close();
outFile = new StreamWriter(outFileName, false, System.Text.Encoding.UTF8);
Overall this seems a bit wasteful. It would be much more efficient to just create the StreamWriter instance one time
outFile = new StreamWriter(outFile, false, System.Text.Encoding.UTF8);
The File.CreateText method is seemingly unnecessary here. If the file doesn't exist StreamWriter will create it

How I can display Stream on the page?

I have a WCF method that I am calling, the method suppose to create a file but it create an exception. I try to find what is in the stream request that I am passing to this method. How I can alert or write this stream so I can find the content. That is my method:
Stream UploadImage(Stream request)
{
Stream requestTest = request;
HttpMultipartParser parser = new HttpMultipartParser(request, "data");
string filePath = "";
string passed = "";
if (parser.Success)
{
// Save the file somewhere
//File.WriteAllBytes(FILE_PATH + title + FILE_EXT, parser.FileContents);
// Save the file
//SaveFile( mtp.Filename, mtp.ContentType, mtp.FileContents);
FileStream fileStream = null;
BinaryWriter writer = null;
try
{
filePath = HttpContext.Current.Server.MapPath("Uploded\\test.jpg"); // BuildFilePath(strFileName, true);
filePath = filePath.Replace("SSGTrnService\\", "");
fileStream = new FileStream(filePath, FileMode.Create);
it produces an error on this line :
fileStream = new FileStream(filePath, FileMode.Create);
that I try to understand why file can not created.
Given the information you gave, I can only assume that your code tries to create the file test.jpg somewhere where your application is not allowed to write. A common mistake would be somewhere in the Program files folder. In modern Windows versions, that is specially protected.

C# - Appending text files

I have code that reads a file and then converts it to a string, the string is then written to a new file, although could someone demonstrate how to append this string to the destination file (rather than overwriting it)
private static void Ignore()
{
System.IO.StreamReader myFile =
new System.IO.StreamReader("c:\\test.txt");
string myString = myFile.ReadToEnd();
myFile.Close();
Console.WriteLine(myString);
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test2.txt");
file.WriteLine(myString);
file.Close();
}
If the file is small, you can read and write in two code lines.
var myString = File.ReadAllText("c:\\test.txt");
File.AppendAllText("c:\\test2.txt", myString);
If the file is huge, you can read and write line-by-line:
using (var source = new StreamReader("c:\\test.txt"))
using (var destination = File.AppendText("c:\\test2.txt"))
{
var line = source.ReadLine();
destination.WriteLine(line);
}
using(StreamWriter file = File.AppendText(#"c:\test2.txt"))
{
file.WriteLine(myString);
}
Use File.AppendAllText
File.AppendAllText("c:\\test2.txt", myString)
Also to read it, you can use File.ReadAllText to read it. Otherwise use a using statement to Dispose of the stream once you're done with the file.
Try
StreamWriter writer = File.AppendText("C:\\test.txt");
writer.WriteLine(mystring);

Categories

Resources