string file path is not working c# - c#

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.

Related

Access to path denied but the file has no restrictions

I'm new to C# and not an expert at programming in general, but I can't seem to figure out what is causing this problem. I am letting the user pick a XML file and then I want to read it's contents. This is in C# making a universal windows 10 app
This is the error I'm getting:
An exception of type 'System.UnauthorizedAccessException' occurred in
mscorlib.ni.dll but was not handled in user code
Additional information: Access to the path 'C:\temp\file.xml' is
denied.
public async static void pickFile()
{
FileOpenPicker openPicker = new FileOpenPicker();
openPicker.ViewMode = PickerViewMode.List;
openPicker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
openPicker.FileTypeFilter.Add(".xml");
StorageFile file = await openPicker.PickSingleFileAsync();
if (file != null)
{
var t = Task.Run(() => { reset(file.Path); });
}
}
then
private static void reset(string path)
{
String LocationDatafilename = path;
XmlReaderSettings settings = new XmlReaderSettings();
XmlReader reader = XmlReader.Create(LocationDatafilename, settings);
XmlDocument LocationDataXml = new XmlDocument();
LocationDataXml.Load(Globals.reader);
}
When I get to XmlReader.Create that's when I'm getting the error. When I look for the cause, the only thing I find is due to permissions, but that isn't the case. Any help would be appreciated. Thanks.
You need to operate on the StorageFile directly, since your app doesn't have permissions to directly read the user's files. You can either use the WinRT XML API or you can keep using the .NET API and use the stream-based Create function instead of the one that takes a file name.
Run sysinternal's ProcMon app, and at the same time run your application. Find the file in the procmon capture, and in the CreateFile entry, you'll find the creation Disposition. This will give you a clue why the creation failed. Also, select the "User" column to show the user performing the operation.
While Peter Torr's answer is correct and is the way Microsoft wants these things to be done, it is possible to make (at least parts of) the OP's code work as well. The reset method will work, if the path is to one of the directories you have permission for. To get these you can use ApplicationData.Current. This object contains properties like LocalFolder, LocalCacheFolder or (what could be interesting for your use case) SharedFolder.

c# Access to path denied?

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.

Reading/Accessing to app settings value issue

Hello I'm trying to access this setting:
with following code:
string path = ConfigurationManager.AppSettings["swPath"].ToString();
StreamReader sr = new StreamReader(File.Open(path,FileMode.Open));
But I get following exception:
Object reference not set to an instance of an object.
May I ask where do I make a mistake? Thank you so much for your time.
Update issue for Ehsan Ullah:
Properties.Settings.Default.swPath = cestasouboru.Text;
Properties.Settings.Default.Save();
I think this isn't that helpful for you but how can I provide more helpful information?
the way you are reading is for AppConfig. Whereas you are reading from the custom settings.
read it like this
string path = Properties.Settings.Default.swPath;
to save it
Properties.Settings.Default.swPath = "your path";
Properties.Settings.Default.Save();

How to give path to an text file in Solution using XDocument?

I want to load a xml document Swedish.xml which exists in my solution. How can i give path for that file in Xamarin.android
I am using following code:
var text = File.ReadAllText("Languages/Swedish.txt");
Console.WriteLine("text: "+text);
But i am getting Exception message:
Could not find a part of the path "//Languages/swedish.txt".
I even tried following lines:
var text = File.ReadAllText("./Languages/Swedish.txt");
var text = File.ReadAllText("./MyProject/Languages/Swedish.txt");
var text = File.ReadAllText("MyProject/Languages/Swedish.txt");
But none of them worked. Same exception message is appearing. Build Action is also set as Content. Whats wrong with the path? Thanks in advance.
Just try with this
string startupPath = Path.Combine(Directory.GetParent(System.IO.Directory.GetCurrentDirectory()).Parent.Parent.FullName, "Languages", "Swedish.txt");
var text = File.ReadAllText(startupPath);
Try...
Environment.GetFolderPath (Environment.SpecialFolder.MyDocuments)+"/Languages/Swedish.txt"
If you mark a file as Content Type, it will be included in the app bundle with the path that you are using within your project file. You can inspect the IPA file (it's just a renamed zip) that is created to verify that this is happening.
var text = File.ReadAllText("Languages/Swedish.txt");
should work. The file path is relative to the root of your application. You need to be sure that you are using the exact same casing in your code that the actual file uses. In the simulator the casing will not matter, but on the device the file system is case sensitive, and mismatched casing will break the app.
I've looked into this before and never found any solution to access files in this way. All roads seem to indicate building them as "content" is a dead end. You can however place them in your "Assets" folder and use them this way. To do so switch the "Content" to "AndroidAsset".
After you have done this you can now access the file within your app by calling it via
var filename = "Sweedish.txt";
string data;
using
(var sr = new StreamReader(Context.Assets.Open(code)))
data = sr.ReadToEnd();
....

IsolatedStorageFile's MoveFile() method throws IsolatedStorageException

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.

Categories