I'm having trouble with an error. I have searched the web but havent found an answer that made sense to me. I'm basically trying to create a temporary text file, and write to it. Here it the code concerning the error:
using ( StreamWriter output = new StreamWriter(File.Create(GetTemporaryDirectory())))
and the getTemporaryDirectory method:
public string GetTemporaryDirectory() {
string tempDirectory = Path.Combine(Path.GetTempPath(), Path.GetRandomFileName());
string tempFile = Path.ChangeExtension(tempDirectory, ".txt");
Directory.CreateDirectory(tempFile);
return tempFile;
}
and last but not least the error:
dir = C:\Users\Jack Givens\AppData\Local\Temp\5ftxwy31.txt
A first chance exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
An unhandled exception of type 'System.UnauthorizedAccessException' occurred in mscorlib.dll
Additional information: Access to the path 'C:\Users\Jack Givens\AppData\Local\Temp\0lpe1k5t.txt' is denied.
If anyone can tell me what is wrong with my code and what i need to do to fix it, I will appreciate it. side note: sorry for crappy code, i'm kinda a beginner :)
Directory.CreateDirectory(tempFile);
You have just created a directory, the name of which ends in "*.txt".
Then you attempt to create a file with the exact same path. But that's not possible.
You call CreateDirectory on your filename so now a folder exists in the path that File.Create is attempting to call. Just simply remove the Directory.CreateDirectory(tempFile); line (it is not needed as the folder is guaranteed to exist) and your code should work.
You are creating a directory, not a file. You can't open a directory as a file.
Related
This is my first time trying to use images in my code. I cannot figure out what file the FromFile command pulls from.
firstDice.Image = Image.FromFile(fDice.ToString() + ".png");
I am trying to get the image to correspond with whatever the random number fDice is.
Here is my error message:
System.IO.FileNotFoundException: '5.png'
Environment.CurrentDirectory
As Steve says in his comment, you must specify the full path otherwise.
You can use Path.Combine to create a path based on the current working directory. Such as:
Path.Combine(Environment.CurrentDirectory, "Images");
I have the following code:
// get location where application data director is located
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// create dir if it doesnt exist
var folder = System.IO.Path.Combine(appData, "SomeDir");
if (System.IO.Directory.Exists(folder) == false)
System.IO.Directory.CreateDirectory(folder);
// create file if it doesnt exist
var file = System.IO.Path.Combine(folder, "test.txt");
if(System.IO.File.Exists(file)== false)
System.IO.File.Create(file);
// write something to the file
System.IO.File.AppendAllText(file,"Foo");
This code crashes on the last line (An unhandled exception of type 'System.IO.IOException' occurred in mscorlib.dll). If I put a Thread.Sleep(400) after creating the file the code works great. What is the proper way of waiting until the file is created?
P.S.
I am using .net framework 3.5
Even if I wait it crashes :/
The reason for that is because File.Create is declared as:
public static FileStream Create(
string path
)
It returns a FileStream. The method is supposed to be used to create and open a file for writing. Since you never dispose of the returned FileStream object you're basically placing your bets on the garbage collector to collect that object before you need to rewrite the file.
So, to fix the problem with the naive solution you should dispose of that object:
System.IO.File.Create(file).Dispose();
Now, the gotcha here is that File.AppendAllText will in fact create the file if it does not exist so you don't even need that code, here is your full code with the unnecessary code removed:
// get location where application data director is located
var appData = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
// create dir if it doesnt exist
var folder = System.IO.Path.Combine(appData, "SomeDir");
System.IO.Directory.CreateDirectory(folder);
// write something to the file
var file = System.IO.Path.Combine(folder, "test.txt");
System.IO.File.AppendAllText(file,"Foo");
Directory.CreateDirectory will likewise not crash if the folder already exists so you can safely just call it.
There is no need to create the file if you intend to use File.AppendAllText
About the root cause for the error, and a preferred way to write to files in general:
The file was created, and returned a stream that you didn't use/close. best method should be to use this stream to write to the file.
using (FileStream fs = File.Create(file))
{
fs.Write("What ever you need to write..");
}
I am using C# to create a function to write data to a file in File System, and reate it and repeat function if file doesn't exist.
The first method of just writing the data is working. But the second method, if the file is not present and the program has to first create it, isn't working. It creates the file but at the very same time throws an exception to me in Visual Studio saying
System.NotSupportedException is unhandled
I am using the exact copy of code that the MSDN is having.
http://msdn.microsoft.com/en-us/library/d62kzs03(v=vs.110).aspx
Here is what I am using in my second code block,
// Create file!
using (FileStream fs = File.Create(file))
{
Byte[] info = new UTF8Encoding(true).GetBytes("some text in the file.");
// Add some information to the file.
fs.Write(info, 0, info.Length);
}
// Continue again with the request.
createFile(file);
The method declaration (if required) is as
private static void createFile (string fileName) {
string file = "C:\\Users\\AfzaalAhmad\\Documents\\" + fileName + ".txt";
/* two methods here */
}
The Image is as: (Note that there is no error in the path of file) I have used
Console.Write(file); // to get the path, and its OK!
See it in the image below ↓
Please note, that it does create the file in the Documents folder. But throws this exception. What am I doing wrong here?
Note the detail in the exception report: "The given path's format is not supported."
Also look at the contents of your variable file - it appears to be #"C:\Users\AfzaalAhmad\Documents\C:\Users..." - i.e. it contains the path twice.
So even though the operating system might have managed somehow to create some sort of file, the filename does not contain a valid value.
[edit] createFile(file); and Console.Write(file); are both taking the value #"C:\Users\AfzaalAhmad\Documents\dsg b.txt" but your method createFile is then adding the path a second time. Change it to simply:
private static void createFile (string file) {
/* two methods here */
}
Please have a exact look at the Exception message and the value of your file variable! There is your error!
Okay I have spent an inordinate amount of time trying to solve what the posts i've read say is a simple fix.
I want to write to a file in my documents and here is my code.
string st = #"C:\Users\<NAME>\Documents\Sample1.txt";
System.IO.StreamWriter file = new System.IO.StreamWriter(st);
file.WriteLine(Convert.ToString(Sample1[0]));
file.Close();
Where is the user name. I am getting the following error
"A first chance exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll. An exception of type 'System.IO.DirectoryNotFoundException' occurred in mscorlib.ni.dll but was not handled in user code"
I am using Visual Studio Express for Windows Phone Development.
If anyone can point out what i am doing wrong i would be grateful.
Thanks.
I assuming you're using the string as you've posted it. If thats the case you should use the SpecialFolder Enum instead.
var st = string.format(#"{0}\Sample1.txt",
Environment.GetFolderPath(Environment.SpecialFolder.Personal));
You should take advantage of the Environment.SpecialFolder enumeration and use Path.Combine(...) to create a path:
var path = Path.Combine(
Environment.GetFolderPath(Environment.SpecialFolder.Personal),
"Sample1.txt");
using (var sw = new StreamWriter(path))
{
sw.WriteLine(Convert.ToString(Sample1[0]));
}
Also, StreamWriter should be placed within a using statement since it is disposable.
To get MyDocuments use:
Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments)
This will return the path to MyDocuments on the host computer.
You can see a list of SpecialFolders on MSDN: http://msdn.microsoft.com/en-us/library/system.environment.specialfolder.aspx
EDIT: I just noticed you were developing for Windows Phone. Read up on the other SpecialFolders on MSDN.
Description:
The code below is the simplest code I could write which causes the failure. I've also tried: putting the CreateFile and MoveFile in different using statements, putting them in different xaml pages, moving the file into a subdirectory with a new filename, moving it into a subdirectory with the same filename. They all throw the same exception. CopyFile throws the same exception in all circumstances.
Question is--what incredibly simple thing am I not accounting for?
Open a new Silverlight for Windows Phone 7 project targeting Windows Phone 7.1.
Open App.xaml.cs.
Paste the following lines of code into Application_Launching:
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
isf.CreateFile("hello.txt");
isf.MoveFile("hello.txt", "hi.txt");
}
Click start debugging, targeting emulator or device.
Expected: creates a file named "hello.txt", then (effectively) renames "hello.txt" to "hi.txt".
Actual: throws exception below.
System.IO.IsolatedStorage.IsolatedStorageException was unhandled
Message=An error occurred while accessing IsolatedStorage.
StackTrace:
at System.IO.IsolatedStorage.IsolatedStorageFile.MoveFile(String sourceFileName, String destinationFileName)
at PhoneApp4.App.Application_Launching(Object sender, LaunchingEventArgs e)
at Microsoft.Phone.Shell.PhoneApplicationService.FireLaunching()
at Microsoft.Phone.Execution.NativeEmInterop.FireOnLaunching()
You should call Close after you create the file.
IsolatedStorageFileStream helloFile = store.CreateFile("hello.txt");
helloFile.Close();
isf.MoveFile("hello.txt", "hi.txt");
I was just having the same issue, but the solution is simple:
The target file must not exists, delete it before the moving. Make sure the target file is not open anywhere before deleting.
The source file must not be open anywhere.
if (_isolatedStorage.FileExists(targetPath))
{
_isolatedStorage.DeleteFile(targetPath);
}
_isolatedStorage.MoveFile(sourcePath, targetPath);
Perfectly execute this piece of code
var file = await ApplicationData.Current.LocalFolder.GetFileAsync(oldName);
await file.RenameAsync(newName);
MBen, your answer is not correct. Calling Close on the file does not fix this error. I am seeing the exact same error as well even though I call "Close" before MoveFile.
edit Ok just figured out the problem I was having - if you try to call MoveFile when the destinationFile already exists, it throws an Exception. You have to delete the destinationFile first before moving your sourceFile to it.