File is being used by another process while using WriteAllText in c# - c#

I am checking file is present if specified location and if so I am replacing single quote by &#39. For this I am using WriteAllText method. For my knowledge WriteAllText will be used to Create file and write the text and close it, target file is already exists, it will be overwritten.
I don't know why I am getting System.IOException while using
var file = AppDomain.CurrentDomain.BaseDirectory + "test";
if (Directory.Exists(file))
{
string text = File.ReadAllText(file + "\\test.txt");
text = text.Replace("'", "&#39");
File.WriteAllText(file + "\\test.txt", text);
}
Note: I am using this inside Application_BeginRequest method.
Suggest me how to avoid this exception ?

Use your code like below
var file = AppDomain.CurrentDomain.BaseDirectory + "test.txt";
if (File.Exists(file))
{
string text = File.ReadAllText(file);
text = text.Replace("'", "&#39");
File.WriteAllText(file, text);
}
Hope this will solve your problem

Firstly,
You are asking on existence of Directory while using
Directory.Exists(file)
In order to check existence of File you need to use
File.Exists(file)
Secondly,
You are trying to ReadAllText from the file by passing as parameter the file concatenated with the file name again. So the file name you are passing is actually:
AppDomain.CurrentDomain.BaseDirectory + "test.txt" + "\\test.txt";
Thirdly, same comment for WriteAllText as for ReadAllText.
There are a lot of examples on the net to learn how to read and write from a file, for example:
Read from a Text File - MSDN
Write to a Text File - MSDN

Related

Copy old file name to new file. C# [duplicate]

This question already has answers here:
Given a filesystem path, is there a shorter way to extract the filename without its extension?
(10 answers)
Closed 5 years ago.
I have searched everywhere to find this answer but still can't find it.
I have a file in my Documents folder. I create and append a file with the same content in another folder. (Let's say Downloads). How do I give the new file the same name as the old file?
I just need help with naming the new file the same as the old. I already have it appending and sending to another folder. I'm using StreamReader to read the old file and StreamWriter to create the new file. I dont want to hard code a path to rename it, because there may be multiple files that I need to read.
It's not clear exactly what you're asking for, but I'll take a stab at it.
If you're using something like the File.Copy() method, then you just have to use the full file path for both the source and destination. If you're passing a string value with the full path to the file, you can get just the file name using Path.GetFileName()
Here's an example based on my loose guesstimation of your question:
var filename = Path.GetFileName(sourcePath);
var newPath = $"{destinationFolderPath}\\{filename}";
File.Copy(sourcePath, newPath);
Additional Reading: https://msdn.microsoft.com/en-us/library/system.io.file.copy(v=vs.110).aspx
https://msdn.microsoft.com/en-us/library/system.io.path.getfilename.aspx
There is a static function Path.GetFilename, which returns a file name contained in a path passed as the argument:
var filename = Path.GetFilename(#"c:\file.txt"); // filename = "file.txt"
Path also contains other useful funtions, such as GetFilenameWithoutExtension.
Use Path.GetFileName i.e.
// The path you want to copy the filename of.
// C:/Users/<username>/Documents/<some file> in your case.
var srcPath = //...
// The directory you want to copy to.
// C:/Users/<username>/Downloads in your case.
var destDir = //...
// Different directory, same filename.
var destPath = Path.Combine(destDir, Path.GetFileName(srcPath));

Invalid Characters in Path while Compression in C#

I am having a problem where I am trying to ZIP up a file using the below code :-
Process msinfo = new Process();
msinfo.StartInfo.FileName = "msinfo32.exe";
string path = "\"" + Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo" + "\"";
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + #"\test.nfo";
MessageBox.Show(path);
msinfo.StartInfo.Arguments = #"/nfo "+path;
//msinfo.Start();
//msinfo.WaitForExit();
//MessageBox.Show("The File Has Been Saved!");
ZipFile.CreateFromDirectory(zippath, #"C:\Test.zip");
MessageBox.Show("Everything Is Done!");
The error that is coming is that the Folder path is not valid. I also tried by including quotation marks in the Zippath variable but it did not work.
PS - My machine name has 3 words so it has got spaces as well. Help is appreciated ^_^
The first argument of ZipFile.CreateFromDirectory should be a path of a directory, not a file (test.nfo in this case).
If you want compress the whole directory (e.g. the Desktop dir) then omit the "test.nfo" from the path, like this:
string zippath = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);
If you want to create a zip archive from only one file then use the ZipFileExtensions.CreateEntryFromFile.
One more thing: when you want to build a path from two or more components use the Path.Combine method instead of simple string concatenation. It can spare you from a lot of pain (like adding path separator characters).

Write file to project folder on any computer

I'm working on a project for a class. What I have to do is export parsed instructions to a file. Microsoft has this example which explains how to write to a file:
// Compose a string that consists of three lines.
string lines = "First line.\r\nSecond line.\r\nThird line.";
// Write the string to a file.
System.IO.StreamWriter file = new System.IO.StreamWriter("c:\\test.txt");
file.WriteLine(lines);
file.Close();
I'm fine with that part, but is there a way to write the file to the current project's environment/location? I'd like to do that instead of hard coding a specific path (i.e. "C:\\test.txt").
Yes, just use a relative path. If you use #".\test.txt" ( btw the # just says I'm doing a string literal, it removes the need for the escape character so you could also do ".\\test.txt" and it would write to the same place) it will write the file to the current working directory which in most cases is the folder containing your program.
You can use Assembly.GetExecutingAssembly().Location to get the path of your main assembly (.exe). Do note that if that path is inside a protected folder (for example Program Files) you won't be able to write there unless the user is an administrator - don't rely on this.
Here is sample code:
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;
string fileName = Path.Combine(path, "test.txt");
This question / answer shows how to get the user's profile folder where you'll have write access. Alternatively, you can use the user's My Documents folder to save files - again, you're guaranteed to have access to it. You can get that path by calling
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
If you want to get the current folder location of your program use this code :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName; // return the application.exe current folder
string fileName = Path.Combine(path, "test.txt"); // make the full path as folder/test.text
Full code to write the data to the file :
string path = Directory.GetParent(System.Reflection.Assembly.GetExecutingAssembly().Location).FullName;
string fileName = Path.Combine(path, "test.txt");
if (!File.Exists(fileName))
{
// Create the file.
using (FileStream fs = File.Create(fileName))
{
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);
}
}

Create file in C# from source code

I'm looking for a way to create a file from a source code (when you open a file in for example notepad it gives you some code, with that code I want to recreate the file, by stating the filetype and filename and then the code that should be in the file.
I hope you can understand my problem, it's a bit hard to explain, I'll go again...
I've got the sourcecode + filename + filetype + file description for the file that I want to create. >
Now I want C# to create a file based on that information and make it an exact copy of what that information is taken from. It should save the file, and then the file is to be openable.
Thank you in advance,
Mike
Write "code" into a file mycode.cs
string code = "code";
string filename = "mycode";
string filetype = "cs";
using (FileStream fs = File.Create(filename+"."+filetype))
{
Byte[] info = new UTF8Encoding(true).GetBytes(code);
fs.Write(info, 0, info.Length);
}
Can you just use the File.Copy method?
file.Copy("c:\temp\source.txt", "c:\temp\dest.txt");

How do I read the file content and sent those content to the functions parameter

I have one function ParseHtmlTable(string htmlContent).
Now in that function I want to pass the content of the html file. Now can I do by writing only filename with its path.Then I have to read that file.But I dont how to read this file ?
Then how to open particular file and read the contents of the file and send those contents to parameter of the function ?
EDIT :
System.IO.File.ReadAllText(path) can read all the html file but there is one file which I have it is not read through this function.What is the reason can be there ? And for that what can be the solution ?
Have you tried using
string s = System.IO.File.ReadAllText( path );
File.ReadAllText Method (String)
EDIT to comment
To itterate the files in a directory you can try using Directory.GetFiles Method (String)
foreach (string filename in Directory.GetFiles(path))
{
//do what you need here
}

Categories