Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 1 year ago.
Improve this question
I am trying to copy a file into another folder, here is my code.
private static void CopyDirectory(DirectoryInfo source, DirectoryInfo target)
{
foreach (var sourceFilePath in Directory.GetFiles(source.FullName))
{
FileInfo file;
if(IsAccesable(sourceFilePath, out file))
{
file.CopyTo(target.FullName); //ERROR HERE
}
else
{
//DO WORKAROUND
}
}
foreach(var sourceSubDirectoryPath in Directory.GetDirectories(source.FullName))
{
DirectoryInfo directory;
if(IsAccesable(sourceSubDirectoryPath, out directory))
{
var targetSubDictionary = target.CreateSubdirectory(Path.Combine(target.FullName, sourceSubDirectoryPath));
CopyDirectory(directory, targetSubDictionary);
}
else
{
//DO WORKAROUND
}
}
}
I keep getting the error message: The target path "" is a directory and not a file
Full sourcePath:
"c:\\Hypixel Bots Interface\\.gitattributes"
Full targetPath:
"C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface"
There is no file in your path. For example, create a file in your folder and name it test.txt an run again your code to verify if the error will disappear.
"C:\Users\wout\source\repos\FileCloner\FileCloner\bin\Debug\net5.0\Target\Hypixel Bots Interface\.gitattributes\test.txt"
As the error says, you want the targetPath to be a file name. You are just pointing to a folder.
"C:\\Users\\wout\\source\\repos\\FileCloner\\FileCloner\\bin\\Debug\\net5.0\\Target\\Hypixel Bots Interface\\.gitattributes"
That would be pointing to a new file in that directory
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 3 years ago.
Improve this question
I am trying to create a folder in a list, the following does not work:
var folder = new DriveItem
{
Name = plan.Title,
Folder = new Folder()
};
await graphServiceClient
.Sites["ourdomain.sharepoint.com:/sites/ITOddeleni:"]
.Lists["Planner"]
.Drive
.Root
.Children
.Request()
.AddAsync(folder);
I am using these as parameters for other calls, can I leave it be or does it expect GUID?
EDIT 1
The ERROR quote is Code:
BadRequest
Message: Url specified is invalid.
So I assume the .Sites and .Lists should have GUID but after replacing the Site URL with Id of site and ID of the list I get the following:
Code: -1, Microsoft.SharePoint.Client.ResourceNotFoundException
Message: Cannot find resource for the request Microsoft.FileServices.FileService/Sites('50cb05fa-27f9-45bf-a5f3-5f82e0e2eb00')/lists('ad52e785-c9b7-4106-af7b-a3394462875c')/drive/.
EDIT 2
I have tried to create the folder via Graph Explorer, found the content type ID for the folder on a list and used POST https://graph.microsoft.com/v1.0/sites/50cb05fa-27f9-45bf-a5f3-5f82e0e2eb00/lists/ad52e785-c9b7-4106-af7b-a3394462875c/items
With this Request body
{
"Title" : "Test2",
"contentType": { "id": "0x012000FC4989A03C9F7845AD8C206E2F47A0FD" }
}
Now the folder gets created, but the call requires Title, but does not accept Name, which results in created folder without Name (title). Edit: It does accept "name"with lowercase N, but still the name is not shown in the list. Tried to send it as "BaseName", "FileLeafRef" and some other internal names of Folder, but without success.
Without an error message, it isn't clear exactly what is happening here. That said, the syntax for creating a new folder should look like this:
var folder = new DriveItem
{
Name = plan.Title,
Folder = new Folder { },
#microsoft.graph.conflictBehavior = "rename"
};
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Closed 5 years ago.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
This question does not appear to be about a specific programming problem, a software algorithm, or software tools primarily used by programmers. If you believe the question would be on-topic on another Stack Exchange site, you can leave a comment to explain where the question may be able to be answered.
Improve this question
Bit of backstory into what I am accomplishing I work as an installation tech for Autodesk and I thought it would be fun to create a simple program to help automate the process of clearing out folders normally left behind after the software is uninstalled.
The directories that I am trying to delete are as followed.
C:\ProgramData\FLEXnet
C:\Program Files\Autodesk\
C:\ProgramData\Autodesk\
C:\Program Files (x86)\Autodesk\
C:\Users\All Users\Autodesk\
C:\Users\**YOUR USERID**\AppData\Roaming\Autodesk\
C:\Users\**YOUR USERID**\AppData\Local\Autodesk\
This is the code that I have been toying arround with
private void btn_start_Click(object sender, EventArgs e)
{
//di.Attributes &= ~FileAttributes.ReadOnly;
try
{
File.SetAttributes("C:/Program Files (x86)/Autodesk", FileAttributes.Normal);
Directory.Delete("C:/Program Files (x86)/Autodesk", true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
try
{
File.SetAttributes("C:/ProgramData/Autodesk", FileAttributes.Normal);
Directory.Delete("C:/ProgramData/Autodesk", true);
}
catch (IOException ex)
{
MessageBox.Show(ex.Message);
}
For the following line it get this error.
File.SetAttributes("C:/Program Files (x86)/Autodesk", FileAttributes.Normal);
System.UnauthorizedAccessException: 'Access to the path 'C:\Program Files (x86)\Autodesk' is denied.'
If I where to remove that line and use the Directoyr.Delete on it's own I would get this error instead.
System.UnauthorizedAccessException: 'Access to the path 'AcIPC_2_x86.dll' is denied.'
I spend a couple of days poking around trying to figure out how I may allow the software the ability to delete the directories but I feel that i'm at an impasse.
Try running the application as administrator through the code, it might be worth a try:
Add a new item to your project folder and call it "Application Manifest File". Then procceed to change this line of code <requestedExecutionLevel> to this:
<requestedExecutionLevel level="requireAdministrator" uiAccess="false" />
This will prompt the user to allow administrator access (So essentially the same as right clicking on it and click run as administrator)
I don't know that this isn't the right place for you. There are reasons why you can get ACCESS_DENIED that can be programmatically overcome. Keep in mind that unless you are an administrator, you cannot remove files or folders from various directories, including Programs and Programs (x86). As fluffy said, you can run as an administrator (if you are an administrator) explicitly because the natural state of an application is to run non-elevated. Here is an example of how I have overcome this problem:
public static class FileSystem
{
public static void RunAsAdministrator(this Process process,
string arguments = "")
{
if (process == null)
{
throw new ArgumentNullException(nameof(process));
}
ProcessStartInfo startInfo = new
ProcessStartInfo(process.MainModule.FileName)
{
Verb = #"runas",
Arguments = arguments
};
Process.Start(startInfo);
public static void TakeOwnership(string path)
{
if (AppDomain.CurrentDomain.IsAdministrator())
{
using (new PrivilegeEnabler(Process.GetCurrentProcess(), Privilege.TakeOwnership))
{
DirectoryInfo directoryInfo = new DirectoryInfo(path);
DirectorySecurity directorySecurity = directoryInfo.GetAccessControl();
if (directorySecurity == null)
{
return;
}
directorySecurity.SetOwner(WindowsIdentity.GetCurrent().User);
Directory.SetAccessControl(path, directorySecurity);
}
}
else
{
Process.GetCurrentProcess().RunAsAdministrator();
}
}
}
public static bool IsAdministrator(this AppDomain threadDomain)
{
threadDomain.SetPrincipalPolicy(PrincipalPolicy.WindowsPrincipal);
WindowsPrincipal currentPrincipal = (WindowsPrincipal) Thread.CurrentPrincipal;
if (currentPrincipal.IsInRole(WindowsBuiltInRole.Administrator) || currentPrincipal.IsInRole((int) WellKnownSidType.AccountDomainAdminsSid))
{
return true;
}
using (WindowsIdentity windowsIdentity = WindowsIdentity.GetCurrent())
{
return windowsIdentity.Groups?.Any(windowsIdentityGroup => windowsIdentityGroup.Value.Equals(#"S-1-5-32-544")
|| windowsIdentityGroup.Value.EndsWith(#"500")
|| windowsIdentityGroup.Value.EndsWith(#"512")) == true;
}
}
}
If you are already running as an administrator, you can take ownership of the directory immediately, otherwise, there is code include to restart the current process in elevated mode.
I CAUTION YOU THAT DOING IS AT YOUR OWN RISK. Taking ownership is a big deal. The other option is to take a less sledge-hammer approach and modify the ACL on the directory or file(s).
The PrivilegeEnabler code is useful regardless. It can be found here.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 7 years ago.
Improve this question
We have a console application name JetIDR. Where we are using log4net for logging log . THis application are currently creating 2 log file JetIDR-INFO.LOG and JetIDR-Debug.LOG .We want to enhance out application to support flexibility on creating log file as below.
Command line parameter should be named as -log
Valid parameter for -loglevel are 1 and 2 only
When parameter 1 is used with -loglevel JetIDR-INFO.LOG file should get created
When parameter 2 is used with -loglevel then JetIDR-INFO.LOG & JetIDR-DEBUG.LOG file should get created
We need to do it in C#.
Your question is effectively "how do I conditionally suppress output to an appender?", where the condition is "If the -loglevel is 1, don't write to the debug logs."
The code would then look like this:
if (logLevel == 1)
{
// assuming appender name is DebugAppender and it is a FileAppender
var appender = log4net.LogManager.GetRepository()
.GetAppenders()
.OfType<FileAppender>()
.SingleOrDefault(a => a.Name == "DebugAppender");
if (appender != null)
{
// Disable the appender
appender.Threshold = Level.Off;
appender.ActivateOptions();
}
}
Note however that if the appender is defined in configuration, the log file is created when log4net is configured: this code thus cannot stop the file from being created, but it will suppress logging to the file.
Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 8 years ago.
Improve this question
i have developed a win application with c# which generate file in a folder in c:\ drive. when try to generate file there then problem occur for permission issue but when the application generate file in other drive than C:\ then no problem occur. so when i will distribute my apps setup to end user then i wont be sure that user who will install my apps does has the permission to generate file in C:\ drive.
so guide me how can i overcome this issue. should i Using Manifests to Elevate an application in win OS?
i got some article
http://blogs.msdn.com/b/nikhiln/archive/2007/04/19/embed-a-manifest-to-make-an-application-elevate-in-vista.aspx
http://www.codeproject.com/Articles/105506/Getting-Elevated-Privileges-on-Demand-using-C
http://archive.msdn.microsoft.com/KB981778
etc......please guide me with right knowledge. thanks
You can start your application again with elevated permission and have some check at the application's start to see if this is the case. Here's an example: (Be careful not to get into an endless loop of the application starting itself.)
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
string[] args = Environment.GetCommandLineArgs();
if (args.Length > 1 && args[1] == "-e") Text = "Elevated";
}
private void button1_Click(object sender, EventArgs e)
{
Process process = new Process
{
StartInfo = new ProcessStartInfo
{
FileName = Application.ExecutablePath,
Arguments = "-e",
Verb = "runas",//-Admin.
}
};
process.Start();
}
}
I agree, though, that storing information in "C:" is probably not a good idea. You can try someplace like: Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData).
Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I went to my project > properties > resources > add existing file > test.bat
Now i have this code :
private void Information()
{
}
I call this function from a button click event.
I want to execute the bat file, so every user which will use my program will be able to execute the bat file directly from the program.
The bat file just create dxdiag.txt in a specific directory.
How can i do that?
You can put the batch file into the executable file folder and then use the Process class like this:
System.Diagnostics.Process.Start(System.IO.Path.Combine(Application.StartupPath, yourBatFileName));
Pay attention that usually your solution is compiled into the Debug folder or into the Release folder depending on your configuration (so you have to put the file in the correct one).
Use this class
Process.Start Method
You can use the following for parameters...
var myProg = new System.Diagnostics.Process();
myProg .StartInfo.FileName = "file name with full path";
myProg .StartInfo.UseShellExecute = false;
myProg .StartInfo.Arguments = "";
myProg .StartInfo.RedirectStandardOutput = true;
myProg .StartInfo.CreateNoWindow = true;
myProg .Start();
myProg .StandardOutput.ReadToEnd().Dump();