Take a look at my code:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
try
{
if (Directory.Exists(Path.Combine(desktopPath, "Hackers.avi")))
Directory.Delete(Path.Combine(desktopPath, "Hackers.avi"), true);
after runing the file is still exist on my desktop , why??
It is unlikely that Hackers.avi is a directory - .avi is normally used an extension for a video file (see Audio Video Interleave on Wikipedia for more information).
Try using File.Delete instead of Directory.Delete:
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
try
{
string pathToFile = Path.Combine(desktopPath, "Hackers.avi");
File.Delete(pathToFile);
// etc...
I also omitted the call to File.Exists because you don't have to check for a file's existence before deleting it. File.Delete does not throw if the file doesn't exist.
You want to delete file, sou you must use 'File.Delete'
Related
I'm trying to use C# to create a file, and read files back to fill out a rich text block. right now my problem is in creating/writing to the file.
FileStream fs = File.Create(#".\\tmp\" + fileName);
This is where I'm trying to write to. .\tmp\ exists, but when trying to write it it errors, saying
.\tmp\filename access is denied
The probably is that the user that is running the application probably doesn't have access to write to that directory. The easiest way to test that would be to run your application as administrator you should have access to write to that directory then.
You might also want to consider writing to the current directory no matter what user who is running your application should at the very least have access to that directory
System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
Probably you don't have access to the relative path.
To get your assembly directory:
private static string AssemblyDirectory
{
get
{
string codeBase = Assembly.GetExecutingAssembly().CodeBase;
UriBuilder uri = new UriBuilder(codeBase);
string path = Uri.UnescapeDataString(uri.Path);
return Path.GetDirectoryName(path);
}
}
Then
FileStream fs = File.Create(Path.Combine(AssemblyDirectory, fileName));
You are using a relative path which leads to a location which you don't have access to.
A possible solution could be to:
Create a folder C:/data and make sure you have read and write rights to that folder
change the code to
string fileName = "file.txt";
FileStream fs = File.Create(#"C:/data/" + fileName);
This should create a file under C:/data with the filename "file.txt", assuming you have the correct read and write rights.
If you want a relative path to the current user's root directory, use:
string currentUserDirectory =
Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
This happened to me . I had had an anti-virus blocking access to any file when the writing or reading process happening from a C# program. I have just deactivated the anti-virus and the code worked like magic !
I need to add a file name/file extension at the end of GetCurrentDirectory. I want to make the .txt file and write text to it
StreamWriter sw = new StreamWriter(Directory.GetCurrentDirectory, );
sw.WriteLine(a + ":Qwerty124");
sw.Close();
Is what i have so far. I want to make the file of the current directory + \example.txt
if the current directory is Sys32 it would look like this
C:\Windows\System32\example.txt
You can use the System.IO.Path.Combine method to append the file name at the end of the path. It essentially does a string append behind the scenes but it is smart enough to use the proper path separator and add it if necessary.
System.IO.Path.Combine(Directory.GetCurrentDirectory(), "example.txt");
Path.Combine
https://msdn.microsoft.com/en-us/library/fyy7a5kt(v=vs.110).aspx
Path.Combine(Directory.GetCurrentDirectory(), "example.txt")
I am trying to open speech recognition in windows
Process.Start("sapisvr.exe");
But not work.
U should path the full path of "sapisvr.exe" to the Process.Start(string path) method.
By default if u dont pass the full path, it starts searching the '.exe' file in current folder(where ur program's exe file is).
For example, use it like this:
Process.Start(#"C:/FolderName/sapisvr.exe");
NOTE: Don't forget to check if the file exist by this:
var filename = #"C:/FolderName/sapisvr.exe"
if (File.Exists(filename))
{
Process.Start(filename);
}
I'm using C# windows application .
I want to save files in my local system.
I used Open File dialog to attach the files.
Here the text inside the file is copying,I want the file itself to get copied with a new name.But what I am really looking for is , it should just save the file automatically and not show the SaveDialog Box?
How it can be done in windows application.Can anybody help me please?
The code is shown below:
private string GetFileName()
{
OpenFileDialog op1 = new OpenFileDialog();
DialogResult result = op1.ShowDialog();
if (result == DialogResult.OK) // Test result.
{
txtEn.Text = op1.FileName;
FileName = op1.FileName;
//MessageBox.Show(FileName);
File.Copy(op1.FileName, #"D:\Backup\");
}
return FileName;
}
SQL Server 2012 seems unrelated to your question. Provided that you have proper access rights to the target directory, then in order to automate the procedure (as per your question) you don't need to use the OpenFileDialog; just a single line should suffice the goal:
//Overwriting a file of the same name is not allowed
File.Copy(FileName, #"D:\Backup\" + FileName)
or
//Overwriting a file of the same name is allowed
File.Copy(FileName, #"D:\Backup\" + FileName, true)
You can also apply some additional logic pertinent to backup file naming (upon necessity).
Hope this may help. Best regards,
Are you trying to copy a file from some x location on your file system to y location (in your case D:\Backup folder) in the file system? If that is the requirement here, I see that you are using the FileName property of OpenFileDialog which gets the File path. This you are appending to D:\Backup. You should instead use the Path.GetFileName property to first extract the file name with extension and then append it to the new folder path
File.Copy(fileName, #"D:\Backup\" + Path.GetFileName(fileName));
I have got this read file code from microsoft
#"C:\Users\computing\Documents\mikec\assignment2\task_2.txt"
That works fine when im working on it, but when i am to hand in this assignment my lecturer isn't going to have the same directory as me.
So i was wondering if there is a way to read it from just the file the program is held in?.
I was thinking i could add it as a resource but im not sure if that is the correct way for the assignment it is meant to allow in any file.
Thanks
You can skip the path - this will read file from the working directory of the program.
Just #"task_2.txt" will do.
UPDATE: Please note that method won't work in some circumstances. If your lecturer uses some automated runner (script, application whatsoever) to verify your app then #ken2k's solution will be much more robust.
If you want to read a file from the directory the program is in, then use
using System.IO;
...
string myFileName = "file.txt";
string myFilePath = Path.Combine(Application.StartupPath, myFileName);
EDIT:
More generic solution for non-winforms applications:
string myFilePath = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location), myFileName);
If it is a command line application, you should take the file name as a command line argument instead of using a fixed path. Something along the lines of;
public static void Main(string[] args)
{
if (args == null || args.Length != 1)
{
Console.WriteLine("Parameters are not ok, usage: ...");
return;
}
string filename = args[0];
...
...should let you get the filename from the command.
You could use the GetFolderPath method to get the documents folder of the current user:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
and to exemplify:
string myDocuments = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
string file = Path.Combine(myDocuments, #"mikec\assignment2\task_2.txt");
// TODO: do something with the file like reading it for example
string contents = File.ReadAllText(file);
Use the relative path.
you can put your file inside the folder where your application resides.
you can use Directory.GetCurrentDirectory().ToString() method to get the current folder of the application in. if you put your files inside a sub folder you can use
Directory.GetCurrentDirectory().ToString() + "\subfolderName\"
File.OpenRead(Directory.GetCurrentDirectory().ToString() + "\fileName.extension")
StreamReader file = new StreamReader(File.OpenRead(Directory.GetCurrentDirectory().ToString() + ""));
string fileTexts = file.ReadToEnd();