Can not open a text file just after creating it from webservice - c#

I am unable to open the file just after creating the file in c# webservice code .
The directory is not present initially. So the program creates the directory and the file. Then tries to open the file to write a line. But it fails to open the file. The error is the file is open in another process.
I tried to open the file from windows explorer. the file opens but error message is still coming.
I tried to delete the folder C:\Test, it says file is open is in WebDev.WebDevServer40.exe
Any help please.
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
if(!File.Exists(completeFileName))
{
Directory.CreateDirectory(path);
File.Create(completeFileName);
}
StreamWriter writer = File.AppendText(completeFileName);
writer.WriteLine(name);
writer.Flush();
writer.Close();
return "success";
}

File.Create returns a stream, but you're discarding it.
So (I think!) you either need to use the returned stream, or explicitly close it before trying to open a new stream to the same file.

You need to close the file, try:
File.Create(completeFileName).Close();

Use the File.AppendAllText instead.
This will create the file if it doesn't exist.
Your code would be as simple as
[WebMethod]
public string saveFileUploaderName(string name)
{
string path = "c:\\Test";
string filename = "Test.txt";
string completeFileName = Path.Combine(path,filename);
File.AppendAllText(completeFileName, name);
return "success";
}

Related

How do I specify a specific file in my Xamarin/VisualStudio Project using Environment.SpecialFolder?

I am trying to append text to a text file, but I can't find anywhere how to actually locate an existing file.
partial void MainBtn_TouchUpInside(UIButton sender)
{
var Pp = ("Selected Form Of Exchange: Paypal");
string mydocpath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments(WHAT DO I WRITE IN THIS SPACE??);
using (StreamWriter outputFile = new **StreamWriter(Path.Combine(mydocpath, "SelectPayment.txt")))
//I know that the file already exists, I just am trying different things.
{
outputFile.WriteLine(Pp);
}
So what do I do? Thanks
Josh
you specify a file by combining a folder path and a file name to create a file path
// this returns the path to a folder
string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments));
// combine that with a file name to create a file path
string file = Path.Combine(path, "myFile.text");
// append text to file
File.AppendAllText(file, "this is the text I want to append);

Copy a specific file (.docx, .pdf, .pptx etc) form folder in C#

I am trying to copy a file (.docx, .pdf, .pptx etc) from a source folder(on server) to a destination folder(on client).
The user can choose which among the list of files that he wants to download. He selects the files and then downloads it(Copies it to his computer) to the destination path
dstnLocation= #"C:\Fldr\Docs;
My Code:
string sourceLocation = textBox2.Text;
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
file.Directory.Create();
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
The problem is that it creates a file as "Docs"(where one has to use open with to open the file) and if I am not wrong then its because of the destination path. Could someone please tell what all am I doing wrong.
The source path is retrieved through database!
you need to concat otherwise you're destination location is just the folder not the file path destination
so do something like
var destFile = string.Format(#"{0}\{1}", dstnLocation, Path.GetFileName(sourceLocation));
then copy that
So code becomes
string sourceLocation = textBox2.Text;
string dstnLocation = string.Format(#"C:\Fldr\Docs\{0}", Path.GetFileName(sourceLocation);
if (! System.IO.Directory.Exists(dstnLocation))
{
System.IO.Directory.CreateDirectory(dstnLocation);
}
System.IO.File.Copy(sourceLocation, dstnLocation,true);
MessageBox.Show("Download Complete");
You are creating the file name incorrectly:
string dstnLocation = #"C:\Fldr\Docs";
System.IO.FileInfo file = new System.IO.FileInfo(dstnLocation);
This creates a file with the name "C:\Fldr\Docs" for example what you want is "C:\Fldr\Docs\myfilename.docx" if I am not mistaken?
Try this instead:
var filename = Path.GetFileName(sourceLocation);
string dstnLocation = Path.Combine(#"C:\Fldr\Docs", filename);
The problem here is that the destination requires an "output" file name.
This problem lies in this line of code
System.IO.File.Copy(sourceLocation, dstnLocation,true);
The dstnLocation needs to be concatenated with the output file name for example:
System.IO.File.Copy(sourceLocation, Path.Combine(dstnLocation,"Database.dbs"),true);

How can I open a specific text file without using OpenFileDialog?

I have a rich text editor that I have created in C#. One of the features I am now trying to add is templates. I do not want the user to have to use an OpenFileDialog to navigate to the template and open the file. I would like to specify the filepath myself so that the user only has to click one button in order to open the template.
Currently, I am trying to achieve this using the following code:
private void formalLetterToolStripMenuItem_Click(object sender, EventArgs e)
{
try
{
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
try
{
if (richTextBoxPrintCtrl1.Modified == true);
{
NewFile();
}
richTextBoxPrintCtrl1.Rtf = fileContents;
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
catch (Exception exception)
{
MessageBox.Show("There was an error opening the template. " + exception, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
However, whenever I try to open the template, I get an exception that is as follows:
System.ArgumentsException: File format is not valid.
However, I have tried to open the file using my OpenFileDialog and that works fine. Could somebody assist me in getting this working correctly?
Your problem is that you're trying to convert the file to a string using str = fileStream.ToString(); however, this converts the filestream to a string which is not the same thing.
Instead just do string fileContents = File.ReadAllText(filepath); to get all of the files contents into a string. You only need to use a FileStream/StreamReader if you're going to do some type of processing on the file.
Also, your use of the FileStream is a little off. I think what you really want is a StreamReader with something like this (example from msdn);
using (StreamReader sr = new StreamReader("TestFile.txt"))
{
string line;
// Read and display lines from the file until the end of
// the file is reached.
while ((line = sr.ReadLine()) != null)
{
Console.WriteLine(line);
}
}
A FileStream cannot be used to read a file. It must be passed to a StreamReader in order to actually read the file and in this case there is no point in doing that because there is an overload of the constructor which takes a filepath. It's only useful if you don't know what kind of stream the reader is going to be reading.
Where you have;
FileStream fileStream = new FileStream(#".\templates\tmp1.rtf", FileMode.Open);
String str;
str = fileStream.ToString();
string fileContents = File.ReadAllText(filepath);
fileContents = fileStream.ToString();
You actually just want thins line; string fileContents = File.ReadAllText(filepath); , nothing else. There is no need for a FileStream when you're just reading all the text into a string.
You are making very heavy weather of loading RTF. Your code to read a file into a string will never work, as #evanmcdonnal explained. Did your file dialog based code that succeeded really do it like that? Remember that a file dialog is just UI that generates a file name in a string. If your code with a file dialog works, then it will work when the file dialog is replaced with a hard coded string.
I suspect that some part of your problem is that you are using a relative path. Perhaps the working directory is not what you expect it to be. You should specify the full path to the file.
In any case, to load RTF simply call the LoadFile method of the control. But I strongly recommend passing the full path to the file.
richTextBoxPrintCtrl1.LoadFile(fullPathToRtfFile);

Sharing violation during save as on Ubuntu Linux

I'm new to C# and I'm having a bit of an issue when saving to a new file. My program has two options for saving: save & save as.
I was getting a sharing violation error when saving, but I fixed that by closing the previous filestream. However, I still cant figure out why my save as code is giving me a sharing violation error.
Here's the code:
// get a file stream from the file chooser
FileStream file = File.OpenWrite(saveFc.Filename);
// check to see if the file is Ok
bool fileOk = file.CanWrite;
if (fileOk == true)
{
// get the filename
string filename = file.Name;
// store the filename for later use
UtilityClass.filename = filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// get a StreamWriter
StreamWriter writer = File.CreateText(filename);
// write to the file
writer.Write(text);
// close/save the file
writer.Close();
file.Close();
}
}
// close the file c
If you could help me figure it out that would be much appreciated. Thanks!
You're opening the same file twice:
FileStream file = File.OpenWrite(saveFc.Filename);
And:
string filename = file.Name;
StreamWriter writer = File.CreateText(filename);
Your code could probably be simplified to:
using (var writer = File.CreateText(saveFc.Filename))
{
// store the filename for later use
UtilityClass.filename = saveFc.Filename;
// get the text from textview1
string text = textview1.Buffer.Text;
// write the text
writer.Write(text);
}
If you open the file with CreateText/OpenWrite it will always be writeable (or an exception will be thrown). The using block will automatically close the writer when it exits.

Formatting a text file, how to update the file after I finished parsing it?

How would I open a file, perform some regex on the file, and then save the file?
I know I can open a file, read line by line, but how would I update the actual contents of a file and then save the file?
The following approach would work regardless of file size, and will also not corrupt the original file in anyway if the operation would fail before it is complete:
string inputFile = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "temp.txt");
string outputFile = Path.Combine(Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments), "temp2.txt");
using (StreamReader input = File.OpenText(inputFile))
using (Stream output = File.OpenWrite(outputFile))
using (StreamWriter writer = new StreamWriter(output))
{
while (!input.EndOfStream)
{
// read line
string line = input.ReadLine();
// process line in some way
// write the file to temp file
writer.WriteLine(line);
}
}
File.Delete(inputFile); // delete original file
File.Move(outputFile, inputFile); // rename temp file to original file name
string[] lines = File.ReadAllLines(path);
string[] transformedLines = lines.Select(s => Transform(s)).ToArray();
File.WriteAllLines(path, transformedLines);
Here, for example, Transform is
public static string Transform(string s) {
return s.Substring(0, 1) + Char.ToUpper(s[1]) + s.Substring(2);
}
Open the file for read. Read all the contents of the file into memory. Close the file. Open the file for write. Write all contents to the file. Close the file.
Alternatively, if the file is very large:
Open fileA for read. Open a new file (fileB) for write. Process each line of fileA and save to fileB. Close fileA. Close fileB. Delete fileA. Rename fileB to fileA.
Close the file after you finish reading it
Reopen the file for write
Write back the new contents

Categories