As an unexperienced developer I have no idea whether this question is phrased properly (I did check the internet but I havent found a solution that worked for me that is why I signed up here). I am trying to make a form where users can upload files to attach to their form (in SharePoint 2013) and I used the following code as an example. The idea is to temporary accept the files and display them to the user and upload them to the document library when the form is submitted.
In my code however, this results in "acces denied" and when I debugged it, the following piece of my code seemed to be causing the problem:
public void BtnAttachmentUpload_Click(object sender, EventArgs e)
{
fileName = System.IO.Path.GetFileName(FileUpload.PostedFile.FileName);
if (fileName != "")
{
string _fileTime = DateTime.Now.ToFileTime().ToString();
string _fileorgPath = System.IO.Path.GetFullPath(FileUpload.PostedFile.FileName);
string _newfilePath = _fileTime + "~" + fileName;
length = (FileUpload.PostedFile.InputStream.Length) / 1024;
string tempFolder = Environment.GetEnvironmentVariable("TEMP");
string _filepath = tempFolder + "\\" + _newfilePath;
FileUpload.PostedFile.SaveAs(_filepath);
AddRow(fileName, _filepath, DocNo, true);
DocNo = DocNo + 1;
Label.Text = "Successfully added in list";
}
}
The last line of the first section(FileUpload.PostedFile.SaveAs(_filepath);) is where it gives the following error:
"System.UnauthorizedAccessException: 'Access to the path
'C:\Users\Spapps\AppData\Local\Temp\131613662837501509~testdoc2.pdf'
is denied.' "
Is this a known issue and is there a solution that can help me out?
Try with spsecurity.runwithelevatedprivileges
I've been looking to close this question but didnt find how to so Ill state it here as an answer. I havent found a solution, but I worked around this issue in my project by altering the approach; I do not temporarily upload and display the files anymore. They are deleted from the doclib if the procedure is cancelled.
Related
So I'm having a problem with automating my code to check-in files to TFS, and it's been driving me up the wall! Here is my code:
string location = AppDomain.CurrentDomain.BaseDirectory;
TfsTeamProjectCollection baseUserTpcConnection = new TfsTeamProjectCollection(uriToTeamProjectCollection);
IIdentityManagementService ims = baseUserTpcConnection.GetService<IIdentityManagementService>();
TeamFoundationIdentity identity = ims.ReadIdentity(IdentitySearchFactor.AccountName, #"PROD1\JR", MembershipQuery.None, ReadIdentityOptions.None);
TfsTeamProjectCollection impersonatedTpcConnection = new TfsTeamProjectCollection(uriToTeamProjectCollection, identity.Descriptor);
VersionControlServer sourceControl = impersonatedTpcConnection.GetService<VersionControlServer>();
Workspace workspace = sourceControl.CreateWorkspace("MyTempWorkspace", sourceControl.AuthorizedUser);
String topDir = null;
try
{
Directory.CreateDirectory(location + "TFS");
String localDir = location + "TFS";
workspace.Map("$/Automation/", localDir);
workspace.Get();
destinationFile = Path.Combine(localDir, Name + ".xml");
string SeconddestinationFile = Path.Combine(localDir, Name + ".ial");
bool check = sourceControl.ServerItemExists(destinationFile, ItemType.Any);
PendingChange[] pendingChanges;
File.Move(sourceFile, destinationFile);
File.Copy(destinationFile, sourceFile, true);
File.Move(SecondsourceFile, SeconddestinationFile);
File.Copy(SeconddestinationFile, SecondsourceFile, true);
if (check == false)
{
workspace.PendAdd(localDir,true);
pendingChanges = workspace.GetPendingChanges();
workspace.CheckIn(pendingChanges, Comments);
}
else
{
workspace.PendEdit(destinationFile);
pendingChanges = workspace.GetPendingChanges();
workspace.CheckIn(pendingChanges, Comments);
}
and the problem is that whenever it's NEW files (PendEdit works correctly when the files already exist in TFS) that my code is attempting to check in, and it runs through this code:
if (check == false)
{
workspace.PendAdd(localDir,true);
pendingChanges = workspace.GetPendingChanges();
workspace.CheckIn(pendingChanges, Comments);
}
The files, instead of being in the included changes in pending changes, are instead in the excluded changes like so:
and when the line that actually does the check-in runs, I'll get a "The array must contain at least one element" error, and the only way to fix it is to manually add those detected changes, and promote them to included changes, and I simply can't for the life of me figure out how to do that programatically though C#. If anyone has any guidance on what direction I should take for this, I would really appreciate it! Thank you!
Edit: I've also discovered another way to solve this by reconciling the folder, which also promotes the detected changes, but again the problem is I can't seem to figure out how to program that to do it automatically.
I know that running the visual studio developer command prompt, redirecting to the folder that this mapping is in, and the running "tf reconcile /promote" is one way, but I can only automate that as far as the /promote part, because that brings up a toolbox that a user would have to input into, which defeats the purpose of the automation. I'm at a loss.
Next Edit in response to TToni:
Next Edit in response to TToni:
I'm not entirely sure if I did this CreateWorkspaceParameters correctly (see picture 1), but this time it gave the same error, but the files were not even in the excluded portions. They just didn't show up anywhere in the pending changes (see picture 2).
Check this blog:
The workspace has a method GetPendingChangesWithCandidates, which actually gets all the “Excluded” changes. Code snippet is as below:
private void PendChangesAndCheckIn(string pathToWorkspace)
{
//Get Version Control Server object
VersionControlServer vs = collection.GetService(typeof
(VersionControlServer)) as VersionControlServer;
Workspace ws = vs.TryGetWorkspace(pathToWorkspace);
//Do Delete and Copy Actions to local path
//Create a item spec from the server Path
PendingChange[] candidateChanges = null;
string serverPath = ws.GetServerItemForLocalItem(pathToWorkspace);
List<ItemSpec> its = new List<ItemSpec>();
its.Add(new ItemSpec(serverPath, RecursionType.Full));
//get all candidate changes and promote them to included changes
ws.GetPendingChangesWithCandidates(its.ToArray(), true,
out candidateChanges);
foreach (var change in candidateChanges)
{
if (change.IsAdd)
{
ws.PendAdd(change.LocalItem);
}
else if (change.IsDelete)
{
ws.PendDelete(change.LocalItem);
}
}
//Check In all pending changes
ws.CheckIn(ws.GetPendingChanges(), "This is a comment");
}
iv made a web forum, as i have lots of folders on my local drive i can now search for any folders i want on webpage.
Now am looking to add a link to the results of the search so it takes me directly to the folder.
My code in c#:
protected void List_Dirs(string searchStr = null)
{
try
{
MainContentLocal.InnerHtml = "";
string[] directoryList = System.IO.Directory.GetDirectories("\\\\myfiles\\Web");
int x = 0;
foreach (string directory in directoryList)
{
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text = "Your Search for : <strong>" + SearchPhrase.Text + "</strong> returns ";
if(directoryP.ToLower().Contains(searchStr.ToLower()))
{
MainContentLocal.InnerHtml += directoryP + "<br />";
x++;
}
}
else
{
MainContentLocal.InnerHtml += directoryP + "<br />";
}
if (searchStr != null && searchStr.Length > 1)
{
UserInfo.Text += "<strong>" + x.ToString() + "</strong> results";
UserInfo.CssClass = "userInfo";
}
}
catch(Exception DirectoryListExp)
{
MainContentLocal.InnerHtml = DirectoryListExp.Message;
}
}
When i enter something is search i will get a list of folders like:
Your Search for : project returns 2 results
job234 project234 Awards
job323 project game
now is there any way for me to click the result so i can open a window explore on the webpage
Thanks
You can create links like project234.
string folder = "\\\\myfiles\\Web";
if (string.IsNullOrWhiteSpace(Request["folder"])) {
// Folder clicked
folder = string.Format("{0}{1}", folder, Request["folder"]);
Process.Start(folder);
}
string[] directoryList = System.IO.Directory.GetDirectories(folder);
Then it will open it on the server. So if it really is local, than it will work. If there is no security problem. But I'm not sure. You can also use file:// links (as Ryan Mrachek notes), but browsers are not happy to let you open them.
If your result is a file, you can open that file programmatically through the Process class by invoking Process.Start("C:\\MyResults.txt"). This will open the results in the default text editor. In the same way, you can also open a web page by inserting passing a Url to Process.Start. I hope this is what wanted.
our file urls are malformed. It should be:
file:///c:/folder/
Please refer to The Bizarre and Unhappy Story of File URLs.
This works for me:
link
When you click Link, a new Windows Explorer window is opened to the specified location. But as you point out, this only works from a file:// URL to begin with.
A detailed explanation of what is going on can be found here. Basically this behavior by design for IE since IE6 SP1/SP2 and the only way you can change it is by explicitly disabling certain security policies using registry settings on the local machine.
So if you're an IT admin and you want to deploy this for your internal corporate LAN, this might be possible (though inadvisable). If you're doing this on some generic, public-facing website, it seems impossible.
Please tell me why file.Delete(gpath) is not working?
i will be very thankful to you :) If there is any error on this code then tell about that error.This code can be wrong so please tell me.
string gpath;
string path=#"c:\Users\Adam\Desktop\";
string name="file";
string f="";
int i=0;
string ext=".txt";
while(File.Exists(path + name + f + ext))
{
i++;
f = i.ToString();
}
gpath = path + name + f + ext;
button2.Enabled = true;
File.Create(gpath);
File.Delete(gpath);//why there is an Error??
File.Create returns a FileStream which you haven't disposed of, so there's an open handle to the file. When you try and delete a file with that has a handle attached to it, you'll get an error saying that the file is in use.
I don't know why you're trying to delete the file straight after creating it so if you explain what you're ultimately attempting to do, there's likely a better way of going about it.
Okay so i am fairly new to programming and was told to just start acouple projects and google/ask if i need hep so here i am, im making a program that will download and run a file from the internet and when i run the release app i get this error http://gyazo.com/7b017f0ed550af3b86b24ad480db8fe8 so i press the details and it give me this long error report thing http://pastebin.com/Ag7u9gBZ i dont seem to have enough knowledge to be able to read and debug it, and i am very confussed, from what i see it has to do with system.io and webclient and path or something i dont know.
private void startBotToolStripMenuItem_Click(object sender, EventArgs e)
{
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21FB6AD2A0A1EB413347302A46C5FB1A39599DF740D6&directstart=1";
WebClient wc = new WebClient();
wc.DownloadFile(direct_exe_from_url, filepath);
Process.Start(filepath);
}
You're getting a System.IO.DirectoryNotFoundException so I would guess that this: C:\Users\Owner\AppData\Roaming\Downloaded Files\ directory does not exist.
You can use the Directory.CreateDirectory method to create the directory before putting the downloaded file in there, e.g:
string directoryPath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\";
string filepath = Environment.GetEnvironmentVariable("AppData") + "\\Downloaded Files\\" + "Minecraft.exe";
if (!Directory.Exists(directoryPath))
{
Directory.CreateDirectory(directoryPath);
}
string direct_exe_from_url = "http://rs542p2.rapidshare.com/cgi-bin/rsapi.cgi?sub=download&fileid=1764003915&filename=Minecraft.exe&cookie=F2CB284BDC9920808D8494CA4EB46F0935AB22D79EC69D6D130C21
//Rest of your code
I have a return a c# code to save a file in the server folder and to retrieve the saved file from the location. But this code is working fine in local machine. But after hosting the application in IIS, I can save the file in the desired location. But I can't retrieve the file from that location using
Process.Start
What would be the problem? I have searched in google and i came to know it may be due to access rights. But I don't know what would be exact problem and how to solve this? Any one please help me about how to solve this problem?
To Save the file:
string hfBrowsePath = fuplGridDocs.PostedFile.FileName;
if (hfBrowsePath != string.Empty)
{
string destfile = string.Empty;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\\\";
if (!Directory.Exists(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)))
Directory.CreateDirectory(FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1));
FileInfo FP = new FileInfo(hfBrowsePath);
if (hfFileNameAutoGen.Value != string.Empty)
{
string[] folderfiles = Directory.GetFiles(FilePath);
foreach (string fi in folderfiles)
File.Delete(fi);
//File.Delete(FilePath + hfFileNameAutoGen.Value);
}
hfFileNameAutoGen.Value = PONumber + FP.Extension;
destfile = FilePath + hfFileNameAutoGen.Value;
//File.Copy(hfBrowsePath, destfile, true);
fuplGridDocs.PostedFile.SaveAs(destfile);
}
To retrieve the file:
String filename = lnkFileName.Text;
string FilePath = ConfigurationManager.AppSettings.Get("SharedPath") + ConfigurationManager.AppSettings.Get("PODocPath") + PONumber + "\\";
FileInfo fileToDownload = new FileInfo(FilePath + "\\" + filename);
if (fileToDownload.Exists)
Process.Start(fileToDownload.FullName);
It looks like folder security issue. The folder in which you are storing the files, Users group must have Modify access. Basically there is user(not sure but it is IIS_WPG) under which IIS Process run, that user belongs to Users group, this user must have Modify access on the folder where you are doing read writes.
Suggestions
Use Path.Combine to create folder or file path.
You can use String.Format to create strings.
Create local variables if you have same expression repeating itself like FilePath.Substring(0, FilePath.LastIndexOf("\\") - 1)
Hope this works for you.
You may have to give permissions to the application pool that you are running. see this link http://learn.iis.net/page.aspx/624/application-pool-identities/
You can also use one of the built-in account's "LocalSystem" as application pool identity but it has some security issue's.