I am trying to write a file on button click event but getting an unauthorized error when trying to do so.
Here is my code:
private void button1_Click(object sender, EventArgs e)
{
{
string path = #"c:\program files\MyTest.txt";
if (!File.Exists(path))
{
// Create a file to write to.
using (StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello");
}
}
// Open the file to read from.
using (StreamReader sr = File.OpenText(path))
{
string s = "";
while ((s = sr.ReadLine()) != null)
{
Console.WriteLine(s);
}
}
}
Getting the error by:
using (StreamWriter sw = File.CreateText(path))
Not sure what i am doing wrong? Could someone please help?
Thanks
By default in Windows a user or a programm started by a user can't write files to every location on a Windows pc.
Maybe try saving your file to a different location.
If that doesn't cut it for you, then you may need to look into running your programm at an elevated permission level
If you just want to save a file for your application the tippical place to do so would be the AppData Folder. The tipcal way of getting its path goes somthing like this:
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData)+"/MyApplicationFolder";
You should change your path to authorize folder like :
string path=Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData);
Related
I am trying to make a text file in my documents
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
StreamWriter sw = File.CreateText(path);
sw.WriteLine("Hello!");
}
It says that path is denied
You're getting an access denied error because File.CreateText() expects a full path to the file that should be created. The code is giving it the path to your Documents folder. Since that path already exists and is a folder, that is the cause of the access denied error.
You should change path to point to a non-existent text file first. Also, StreamWriter.Dispose() needs to be called in order to close the file (this is typically done with a using statement).
private void SaveButton_Click(object sender, EventArgs e)
{
string path = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
path = Path.Combine(path, "MyFile.txt");
using(StreamWriter sw = File.CreateText(path))
{
sw.WriteLine("Hello!");
}
}
You have not given the path to the file you are trying to create; only the folder itself. Instead you could do something like
using (StreamWriter sw = File.CreateText(path + $"\hello.txt"))
sw.WriteLine("Hello!");
I'm pretty new to C# and I'm experimenting a lot, I'm trying to make my program a little more user friendly and that is where the problem starts.
At first the location of the excelfile was in a public static string and I had no problems. I've changed it to this:
public string Excellocation()
{
string xlLocation;
if (but_Browse.Text == "Zoek Excel")
{
xlLocation = #"E:\Levi\Documents\Verjaardagen.xlsx";
}
else //Only if I get into this part of my code I get the error
{
xlLocation = but_Browse.Text;
}
return xlLocation;
}
And the button I use so the user can give me a location for the excel file is:
private void but_Browse_Click(object sender, EventArgs e)
{
var FD = new System.Windows.Forms.OpenFileDialog();
if (FD.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
string fileToOpen = FD.FileName;
System.IO.FileInfo File = new System.IO.FileInfo(FD.FileName);
//OR
System.IO.StreamReader reader = new System.IO.StreamReader(fileToOpen);
//etc
but_Browse.Text = fileToOpen;
this.but_Browse.AutoSize = true;
But_Import.Visible = true;
}
}
Reading the Excel-file is no problem, my program finds it and processes it, if and only if the user changed the location by using the "Browse button" I get a message from Windows that there is already an excel file with that name and if I want to replace it, If I click away that message, my code gives an error on the line that tries to save the excel file
xlWorkbook.Save();
xlWorkbook.Close(true);
xlApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(xlApp);
xlWorkbook.Save() gives me this error:
System.Runtime.InteropServices.COMException occurred
HResult=0x800A03EC Message=Verjaardagen.xlsx can not be saved,
because it's read-only.
I have no idea why I don't get an error with the default location while I do get an error if use my button to give me that same location.
Does anyone know what i'm doing wrong?
Thanks in advance
So the problem is that the file is read only when you try to write to it after going through but_Browse_Click? Are you closing the StreamReader? Try using
reader.close();
in but_Browse_Click.
Perhaps a better way would be:
using (StreamReader reader = new StreamReader(fileToOpen))
{
//all code involving the reader in here
}
This automatically closes on completion.
Im trying to write a console application in order to store a single image from a given path into a new directory as suggested in this article. Despite my program not throwing out any errors the image I want to download just won't show up in my folder. I guess that's because I never told my program where I want the file to be saved? However, I haven't found anything clarifying this particular problem I have right now. I already referred to this and this question, too.
using System;
using System.IO;
using System.Net;
namespace GetImages
{
class Program
{
static void Main(string[] args)
{
string dirPath = #"C:\Users\Stefan\Desktop\Images";
try
{
// Create a new directory
DirectoryInfo imageDirectory = Directory.CreateDirectory(dirPath);
Console.WriteLine($"Directory '{Path.GetFileName(dirPath)}' was created successfully in {Directory.GetParent(dirPath)}");
// Image I'm trying to download from the web
string filePath = #"http://ilarge.lisimg.com/image/12056736/1080full-jessica-clements.jpg";
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.GetFileName(filePath));
_wc.Dispose();
}
Console.WriteLine("\nFile successfully saved.");
}
catch(Exception e)
{
while (e != null)
{
Console.WriteLine(e.Message);
e = e.InnerException;
}
}
if (System.Diagnostics.Debugger.IsAttached)
{
Console.WriteLine("Press any key to continue . . .");
Console.ReadKey(true);
}
}
}
}
Edit: After some time I figured out that the file is saved in "C:\Users\Stefan\Documents\Visual Studio 2017\Projects\GetImages\GetImages\bin\Debug". But how do I get the file to be saved directly to dirPath without moving them from Debug to dirPath separately? My next step would be extending this program to save multiple files at once.
The second argument of DownloadFileAsync is the save location so combine the path you create and the filename from the URL:
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath, Path.GetFileName(filePath)));
Try this:
using (WebClient _wc = new WebClient())
{
_wc.DownloadFileAsync(new Uri(filePath), Path.Combine(dirPath,Path.GetFileName(filePath)));
}
How to get path by environment variable to get file:
string path = (#"%ProgramData%\\myFolder\\textdoc.txt");
to run file by environment variable path:
Process.Start(#"%ProgramData%\\myFolder\\file.exe");
Here is how you can create folder,file and write text in it. Once file is created and written, it will be opened in notepad.
private void button1_Click(object sender, EventArgs e)
{
string basePath = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData);
string myDir = Path.Combine(basePath, "myFolder");
if (!Directory.Exists(myDir))
{
Directory.CreateDirectory(myDir);
}
string myFile = Path.Combine(myDir, "textdoc.txt");
using (FileStream fs = File.OpenWrite(myFile))
{
using (StreamWriter wrtr = new StreamWriter(fs, Encoding.UTF8))
{
wrtr.WriteLine("This is my text");
}
}
Process.Start("notepad.exe", myFile);
}
Note : Way file is created and written in above code will always overwrite file content. If you need to append new content then you should use different constructor of StreamWriter and pass append parameter as true.
Also you need admin permission to create folder/file inside "ProgramData" folder.
In my application the user can drag and drop multiple text files onto a GUI control to convert them to another format. Here is the relevant code:
private void panelConverter_DragDrop(object sender, DragEventArgs e)
{
string[] filenames = (string[])e.Data.GetData(DataFormats.FileDrop);
foreach (string filename in filenames)
{
convertFile(filename);
}
}
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
StreamWriter dstStream = new StreamWriter(convertedFile);
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
The problem is that when I drop multiple files on the GUI, only one of them actually gets processed. I have found that if I comment out the Regex line, all of the dropped files are processed. Am I missing something in my handling of regular expressions in this context?
Try following variation of the method:
private void convertFile(string filename)
{
// build name of output file
string convertedFile = Path.ChangeExtension(filename, ".out");
// open input file for reading
FileInfo source = new FileInfo(filename);
StreamReader srcStream = source.OpenText();
// open output file for writing
using (StreamWriter dstStream = File.CreateText(convertedFile))
{
// loop over input file
string line;
do
{
// get next line from input file
line = srcStream.ReadLine();
if (!Regex.IsMatch(line, #"fred=\d+"))
{
dstStream.WriteLine(line);
dstStream.Flush();
}
} while (line != null);
}
Debug.WriteLine(string.Format("File written to: {0}", convertedFile));
}
The main modification is use of using keyword which would guarantee disposal and closing of the file resource. If problem is not still resolved then try followings:
Do you have any global exception handlers? Make sure you check Debug > Exceptions... so that Visual Studio automatically breaks on the line where exception is thrown. See this article on how-to.
Make sure files are written at correct places. If files have full path then the Debug.WriteLine statement above would tell you were the files are being written.
You should get at least 0 length file written on the disk if no exceptions are occurring.