Attaching Data with FILESTREAM Direcotry - Access Denied

I am trying to develop a configuration program that attaches a SQL Server R2 Express database that includes FILESTREAM columns. The attach works fine if I manually  give the NT AUTHORITY/NETWORK SERVICE account full privileges to the FILESTEAM
folder using File Explorer.   NT AUTHORITY/NETWORK SERVICE  is the account that my SQL Server process runs under.  However when I try to grant the privilege in my configuration program the privileges are not granted.
This is the code I am using to grant the privileges:
public static void GrantFullRightsToNetWorkService(string folder)
// This gets the "Network Service" sid, no matter what it's called
SecurityIdentifier sid = new SecurityIdentifier(WellKnownSidType.NetworkServiceSid, null);
// Create the rules
FileSystemAccessRule allrule = new FileSystemAccessRule(sid, FileSystemRights.FullControl, AccessControlType.Allow);
if (!string.IsNullOrEmpty(folder) && Directory.Exists(folder))
// Get your file's ACL
DirectorySecurity fsecurity = Directory.GetAccessControl(folder);
// Add the new rule to the ACL
fsecurity.AddAccessRule(allrule);
// Set the ACL back to the file
Directory.SetAccessControl(folder, fsecurity);

I am not sure that .NET code for setting Windows permissions is within the scope for this forum.
But why attach? Why not restore of a backup instead?
Erland Sommarskog, SQL Server MVP, [email protected]

Similar Messages

  • InfoPath 2013 Read SharePoint 2013 File data using Rest API Access Denied Exception

    I am designing a set of Forms and they need to query Data from among themselves.
    The whole set up described below works in the Form Filler/Preview
    I'll call them Form A and Form B
    Form A has a repeating table that needs to be displayed in Form B
    The user selects from a DropDown in Form B an Instance of Form A, using the selected I REST connection is executed so the Form A xml is available inside Form B. The connection is set up as follows:
    _api/web/lists/ListName/Items(SelectedId)/File/$value
    I publish the form as site content type, add it to a library, after triggering the REST connection I get an error. ULS gives me a 401 Access denied for NT Authority\IUSR (as it should since I don't have anonymous access enabled [nor has that solved the issue])
    That's my issue. All requests on the REST api are being executed as anonymous and not as a user that should have permission.
    Things I've tried:
    1. The connection uses a UDCX file, the conenction is set to use the form server proxy. The proxy has been enabled for the Form Services, web application and user connection. I've tried it with a configured App ID or an Explicit account
    2. I've tried enabling Anonymous access, but have had no success
    3. I've gotten the Query to work on Post Backs by adding the following to the web.config:
    <location path="_layouts/15/Postback.FormServer.aspx">
        <system.web>
          <identity impersonate="false" userName="bhs\sp_admin_dev" password="M1crosoft" />
        </system.web>
      </location>
    And while it solves the issue for Postback requests and I could add FormServer.aspx to the list I can't use this solution for a production environment, nor can I predict other issues that could be caused by the change.
    I haven't been able to find any references to this error so I wonder if I'm doing something wrong or if there's another way to do this.
    If I've been unclear on anything, let me know and I'll try to clear it up.

    Hi Choggo,
    thank you for your information,
    regarding this issue, it seems we may need to debug and trace your network, to check if should the parameter that is used for the REST connection is correct.
    i checked with infopath team members regarding this issue, they suggest that you try with impersonation, so that the user that login is not anonymous, but the user that you already been assign with.
    the last suggestions from our sharepoint team members that we are able to do, as we have limited tools on this forum support, that you need to check the file udcx itself, do the permission to access that file is correct, so for example, if the file is not
    having the permission to be read/access then the system may result with anonymous account, so that we may have the result that the data that should be passed are able to accessed.
    if should this suggestion not applicable to your environment, our sharepoint team members suggest that you to open an incident ticket, so that we can check and re-confirm more deep for you if should this is an undocumented feature or not.  the action
    plans is to have a remote session, then we can trace the data passing process, that is already correct, so that the IUSR is not appear when it authenticate.
    http://support.microsoft.com/contactus/?wa=wsignin1.0
    Regards,
    Aries
    Microsoft Online Community Support
    Please remember to click “Mark as Answer” on the post that helps you, and to click “Unmark as Answer” if a marked post does not actually answer your question. This can be beneficial to other community members reading the thread.

  • Dealing with a sudden access denied situation on some of the sites on our dev farm.

    This morning we suddenly found that we could not access the top level site of our dev site collection. In fact, we have found there are quite a number of other sites we cannot access. We have yet to find any user who is able to access the top of the site.
    Farm admins, site collection admins, etc. all get access denied to the top level.
    The farm has 3 site collections. The root site collection prevents us from seeing the top site, but at least one secondary site on the collection is viewable by those with permissions. Another of them appears to allow the top level and a number of the second
    level sites - the ones we have had time to check.  The third site collection allows us access to the top level, but we have not found any second level sites that we can access.
    I really am having a tough time figuring out any pattern.
    There is nothing obvious in the event or ULS logs that correspond to the access denied messages.
    I have seen, on the net, references to issues with the portalsuperuseraccount and the portalsuperreaderaccount values.
    I ran commands to set those to the proper values.  No change in the behavior was seen. And I would not expect those to cause sporadic problems - I would think that nothing would be accessible rather than "random" sites.
    Do you have any ideas what might be be able to be done to fix such a thing?
    Thank you

    Is this a SharePoint 2010 site or 2013?
    In both 2010 and 2013
    Try and access the site with the account that is running the application pool in IIS.  e.g. when the web application that holds the site collection was created an application pool was chosen and a user account to run that pool was given.  Check
    in IIS and see what that account is and use that account.
    In 2013,
    I had a similar issue with 2013.  And somehow, the site collection admins were modified at the site level versus the site collection level, if you can believe that.  So there was discrepancy between what showed in central admin > application
    management > change site collection admins and what showed when in the site collection, looking at site settings, site collection admins.
    once initial site collection admins that were listed on central admin.... were added, access was restored.
    Stacy www.sharepointpapa.com

  • Filling Item Attached Data with Order Information

    Hello Experts,
    we run CRM 7.0 with EHP and have out Interaction Center connected to the CCS Simulator and it works pretty good.
    We can demo varios szearions like incomming calls with automatic customer identification and forwarding the call to another agent including the customer information.
    Now I want to include the Reference to a started order into the item attaced date such that the receiving agent gets the order and can complete it.
    But I just do not manage ti include the Orderreference into the item attached date.
    Can anybody help me?
    Thanks a lot.
    Michael Schöne.
    Edited by: Michael Schöne on Mar 10, 2011 3:57 PM

    Hi Michael,
    Kalees is right, in order to include Orderreference into the Item Attahced Data you need to add this variable as a KVP (Key Value Pair) in your XML file on the CMS side.
    Also, you have to add it in the CRM configuration for yoru CAD Group profile (for your Business Role) - transaction CRMC_IC_CAD.
    Below, the  <Application id="Genesys-CAD"> - is the name that has to be the same as CAD Group profile in CRMC_IC_CAD.
    After customer calls and enters the Order reference thru IVR, the result of XML will like like this:
    <?xml version="1.0" encoding="iso-8859-1"?>
    <ItemAttachedData>
    <Application id="Genesys-CAD">
    <BPNUMBER>12356</BPNUMBER>
    <CALLTYPE>Outage/CALLTYPE>
    <ORDERREFERENCE>zzz</ORDERREFERENCE>
    </Application>
    </ItemAttachedData>
    It'salso nice to display the CAD in teh Alerts area, like Kalles mentioned, if you have EhP1 and enabled the Business function profile framework switch CRM_IC_CEBP (transaction SFW5).
    Regards,
    Vadim.

  • Cannot use Offline Files with DFS share: "Access denied" error for DfsrPrivate in Sync Center

    Hello,
    I have an infrastructure that uses DFS to move files to different sites and we are using a GPO to define Offline Files for users at those sites. Whenever we try to initiate a manual sync, an error stating "Access
    denied" is generated for all DfsrPrivate directories and the Sync Center reports it as a failed sync. We have tried giving Domain Users, Everyone, and invidiual accounts Write, Modify and even Full Control permissions to the DfsrPrivate directories and
    as it seems, only users with administrative access and allowed to sync properly. Is there something obvious I'm missing here?
    -Girard

    Hi,
    I cannot help test on this moment but we should not create offline files on DfsrPrivate folders which will cause issue. Try to exclude those folders as Offline Files and it should work in Sync Center. 
    If you have any feedback on our support, please send to [email protected]

  • urgent insert Date with Time into Access Database

    i found the following codes from the forum to insert date into microsoft access database:
    java.sql.Date date = new java.sql.Date((new java.util.Date()).getTime())
    stmt.executeUpdate("INSERT INTO Testing " +"VALUES (#"+date+"#)");
    but i need to insert the date together with its time so may i know how can i do it?

    thanks alot i works... but it allow only one value to be inserted.
    so i try the codes below:
    Timestamp ts=new Timestamp(tryDate.getTime());
    PreparedStatement p = connection.prepareStatement("insert into testing values(?,?)");
    p.setTimestamp(1,ts);
    p.setString(2,theMsg.getContent());
    p.executeUpdate();
    and error is this:
    java.sql.SQLException: [Microsoft][ODBC Microsoft Access Driver] Number of query values and destination fields are not the same.
         at sun.jdbc.odbc.JdbcOdbc.createSQLException(JdbcOdbc.java:6106)
         at sun.jdbc.odbc.JdbcOdbc.standardError(JdbcOdbc.java:6263)
         at sun.jdbc.odbc.JdbcOdbc.SQLExecute(JdbcOdbc.java:2564)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.execute(JdbcOdbcPreparedStatement.java:214)
         at sun.jdbc.odbc.JdbcOdbcPreparedStatement.executeUpdate(JdbcOdbcPreparedStatement.java:136)
         at DBIncomingQueue.insertMessage(DBIncomingQueue.java:84)
         at DBIncomingQueue.main(DBIncomingQueue.java:213)

  • Unity Connection 8.5 single inbox with Exchange 2003 - Access denied

    Hi,
    I'm using CUCMBE 8.5.1.12900-7 Unrestricted. i'm following Unified Messaging Guide for Cisco Unity Connection Release 8.5 and Later for configuring single inbox. I have successfully setup and tested unified messaging service when I subscribe this service to a particular user and test it, I get following error:
    Issue: Failed accessing [email protected] on 192.168.0.10
    Recommendations: Some possible reasons for 401: Incorrect service account name or password. Service account password expired. Proper permissions not granted to service account. Exchange mailbox uninitialized.
    Details: HTTP status=[401 Unauthorized] diagnostic=[Bad response from server, HTTP code returned: 401] url=[http://192.168.0.10/exchange/
    [email protected]] request=[<?xml version="1.0"?> <D:propfind xmlns:D="DAV:" xmlns:fh="urn:schemas:httpmail:" xmlns:h="http://schemas.microsoft.com/repl/"> <D:prop> <fh:msgfolderroot/> </D:prop> </D:propfind> ] response=[<html><head><title>Error</title></head><body>Error: Access is Denied.</body></html>]
    I have verified above mentioned recommendations but no such issue exists. Any ideas?

    Hi Muhammad,
    I am having exactly the same issue in configuring sinlgle inbox with unity connection 8.6 and exchange 2003. I have checked everything but no result. Could you please help in configuring?
    Thanks
    The validation results for the  user unified messaging service account [email protected] with service  E2K302 are the following:
    Service "E2K302":  AuthenticationMode=NTLM [use HTTP] Server=[E2K3-02.chelloit1.local]  Type=[Exchange 2003] Username=[chelloit1.local\agokharu]
    Failed accessing  [email protected] on E2K3-02.chelloit1.local
    Some possible reasons for 401:  Incorrect service account name or password. Service account password expired.  Proper permissions not granted to service account. Exchange mailbox  uninitialized.
    HTTP status=[401 Unauthorized]  diagnostic=[Bad response from server, HTTP code returned: 401]  url=[http://E2K3-02.chelloit1.local/exchange/[email protected]]  request=[<?xml version="1.0"?> http://schemas.microsoft.com/repl/">   ]  response=[ErrorError:  Access is Denied.]

  • Create event in GOS obj to trigger workflow while attaching data with GOS

    Hello experts,
    It is a little bit urgent.
    I have a scenario. We have to attach documents to SAP application using GOS. These documents can be edited also.
    Now second part is that when we attach the document or edit the document, the document should be send with the work item "when we attach the document".
    The first part of the scenario is completed and working fine. The second part of the scenario is causing problem. I have checked the various options but none of them are proving helpful.
    There is an option in GOS toolbar to send the documents through workflow but that also asks for the related workflow.
    I was trying to create an event for GOS object (Z object not a subtype of any other object) which can trigger the workflow automatically when the attachment are created and edited but can not go further with it as am not so strong in workflow. I ahve just created the event. Do I need to write some code for the event?
    I request you to kindly help me either in creating this event which will trigger the workflow (whole process) or any other method to do the same.
    Thank you all in advance.

    Hello Arghadip,
    Thank you for replying so early. The table point is very helpful but about the batch job I do not get it. I think the second option is good trigerring event on updation of table. But again I do not know how to do it as I have customized object so have to create the event from the scratch and that, sir, is my main problem.
    Kindly help.
    Thank you

  • Access denied by Business Data Connectivity when trying to add myself to the BDC Metadata Store

    Originally I was trying to create a ECT in SharePoint Designer 2010, on the production server, and every attempt fails with the error "Access denied by Business Data Connector" and I found the post "Deploying a BDC Model project to SharePoint 2010"
    which suggests that I may not have rights to the BCD Metadata Store: "It seems that an account are you using to deploy solution doesn't have sufficient permission in the BDC Metadata Store."
    So I tried to set myself (individual windows user) up to have rights via:  "Central Administration->Application Management->Manage Service Application->Business Data Connectivity Service->Click Set Metada Store Permission
    on the ribbon->Set Permission you need and tick the checkbox "Propagate permission to all"; and pressing the OK button an error dialog displays stating Access denied by Business Data Connectivity.
    What should I check next?

    I'm in a situation similar to MarkDavisHQ's.  I was able to get the Metadata Store working by:
    Making the BDC app pool identity a local administrator (before that, I was seeing lots of WcfSendRequeust like this in the logs - but I'm still not sure this escalation was necessary.   I have since removed the app pool identity from local administrators
    and it ):
    Starting the (SharePoint) Claims to Windows Token Service
    Can anyone else confirm whether or not local admin privileges are required?
    For those who may be stuck at a similar spot,  here are the log excerpts that helped me.
    Before I changed the local admin membership, this was appearing in the logs:
    04/22/2012 15:03:26.62    w3wp.exe (0x0FFC)    0x0DF4    SharePoint Foundation    Runtime    tkau    Unexpected    Microsoft.BusinessData.Infrastructure.AccessDeniedException:
    Access denied by Business Data Connectivity.    at Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplicationProxy.Execute[T](String operationName, UInt32 maxRunningTime, ExecuteDelegate`1 operation, Boolean performCanaryCheck, Boolean
    isChannelThatDelegatesIdentity)     at Microsoft.SharePoint.BusinessData.SharedService.BdcServiceApplicationProxy.SetAccessControlEntries(MetadataObjectStruct metadataObjectStruct, AccessControlEntryStruct[] aces, String settingId)    
    at Microsoft.SharePoint.BusinessData.Infrastructure.BdcAccessControlList.SaveAs(MetadataObjectStruct metadataObjectStruct, String settingId, BdcServiceApplicationProxy serviceProxy)     at Microsoft.SharePoint.BusinessData.Administration.IndividuallySecurableMetadataObject.SetAccessControlList(IAccessControlList
    acl, String settingId)     at Microsoft.SharePoint.ApplicationPages.ManageBDCPermissions.OkButton_Click(Object sender, EventArgs e)     at System.EventHandler.Invoke(Object sender, EventArgs e)    
    at System.Web.UI.WebControls.Button.OnClick(EventArgs e)     at System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument)     at System.Web.UI.Page.RaisePostBackEvent(IPostBackEventHandler sourceControl,
    String eventArgument)     at System.Web.UI.Page.ProcessRequestMain(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)    c448101d-363b-4e70-bac4-3ffb0c3313dc
    After I changed the membership, I hit this one (which was resolved by starting the Claims to Windows Token Service ):
    04/22/2012 21:50:44.54    w3wp.exe (0x1030)    0x0CF4    SharePoint Foundation    Claims Authentication    bz7l    Medium    SPSecurityContext.WindowsIdentity:
    Could not retrieve a valid windows identity for NTName='XYZDEV1\e-hugh.kelley', UPN='[email protected]'. UPN is required when Kerberos constrained delegation is used. Exception: System.ServiceModel.EndpointNotFoundException: There was no endpoint listening
    at net.pipe://localhost/s4u/022694f3-9fbd-422b-b4b2-312e25dae2a2 that could accept the message. This is often caused by an incorrect address or SOAP action. See InnerException, if present, for more details. ---> System.IO.PipeException: The pipe endpoint
    'net.pipe://localhost/s4u/022694f3-9fbd-422b-b4b2-312e25dae2a2' could not be found on your local machine.      --- End of inner exception stack trace ---    Server stack trace:      at System.ServiceModel.Channels.PipeConnectionInitiator.GetPipeName(Uri
    uri)     at System.ServiceModel.Channels.NamedPipeConnectionPoolRegistry.NamedPipeConnectionPool.GetPoolKey(EndpointAddress address, Uri via)     at System.ServiceModel.Channels.CommunicationPool`2.TakeConnection(EndpointAddress
    address, Uri via, TimeSpan timeout, TKey& key)     at System.ServiceModel.Channels.ConnectionPoolHelper.EstablishConnection(TimeSpan timeout)     at System.ServiceModel.Channels.ClientFramingDuplexSessionChannel.OnOpen(TimeSpan
    timeout)     at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan timeout)     at System.ServiceModel.Channels.ServiceChannel.OnOpen(TimeSpan timeout)     at System.ServiceModel.Channels.CommunicationObject.Open(TimeSpan
    timeout)     at System.ServiceModel.Channels.ServiceChannel.CallOnceManager.CallOnce(TimeSpan timeout, CallOnceManager cascade)     at System.ServiceModel.Channels.ServiceChannel.EnsureOpened(TimeSpan timeout)    
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean oneway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan timeout)     at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
    methodCall, ProxyOperationRuntime operation)     at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)    Exception rethrown at [0]:      at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
    reqMsg, IMessage retMsg)     at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgData, Int32 type)     at Microsoft.IdentityModel.WindowsTokenService.S4UClient.IS4UService_dup.UpnLogon(String
    upn, Int32 pid)     at Microsoft.IdentityModel.WindowsTokenService.S4UClient.<>c__DisplayClass1.<UpnLogon>b__0(IS4UService_dup channel)     at Microsoft.IdentityModel.WindowsTokenService.S4UClient.CallService(Func`2
    contractOperation)     at Microsoft.SharePoint.SPSecurityContext.GetWindowsIdentity().    090b18ec-3a6f-4367-a74b-b6a113a62507
    04/22/2012 21:50:44.54    w3wp.exe (0x1030)    0x0CF4    SharePoint Foundation    Claims Authentication    g220    Unexpected    No windows identity
    for xyzdev1\e-hugh.kelley.    090b18ec-3a6f-4367-a74b-b6a113a62507

  • JSF Page Access Denied for Jdeveloper 12 C

    I had using J developer 12 C and Created one JSF page with Displaying two tables on that page... The content not displaying it shows Access Denied.

    Is it related webcenter portal.I don't think so. If it is pure ADF problem.You can post this in jdeveloper forum too.
    Is there any security restriction on the table by adf security or some other security.
    In the table source code in empty text property it is mentioned as
    <af:table   emptyText="#{bindings.abcTable.viewable ? 'No data to display.' : *'Access Denied.'*}"

  • "Access Denied" opening PDF from network UNC path.

    Can't open pdf file from network path when opening from Adobe Reader any versions. Opening other files such as word, excel etc that is not opening in Adobe Reader works just fine.
    Steps to reproduce bug:
    Create a shared folder with three folder deep. \\Servername\SharedDrive\FolderLevel1\FolderLevel2\FolderLevel3\
    Give user explicit access to "FolderLevel3" with read and execute rights
    Enabled "Protected Mode at StartUp" on Adobe Reader X or XI
    Make sure there are some PDF files in FolderLevel3
    On the user windows session "do not map the share drive", open explorer to "\\Servername\SharedDrive\FolderLevel1\FolderLevel2\FolderLevel3\" directly.
    Double click the PDF files in the folder and it will be blocked with an error Access Denied.
    Turn off Protected Mode at StartUp and it load fine
    Map the location to a Drive Letter and it load fine
    Use Adobe Professional and it works fine
    Use Nuance PDF reader and it works fine
    Not the ideal solution but if we gave users access to read at "SharedDrive" folder, FolderLevel1 and FolderLevel2 then they are able to read the PDF file. We would rather NOT DO THIS. They are blocked from the lower level for a reason......
    Results:
    Expected results: If it works on PRO it should work on Reader...

    Hi Ayenoy,
    Please provide the following information:
    1) Adobe Reader version on your machine.
    2) OS you are using.
    3) Is your machine or the shared drive a part of any special file system like DFS etc.
    4) Is the user a normal admin/standard user or a special user with roaming profile and folder redirections?
    Thanks,
    Shakti K

  • SQL Server 2012 SP2 NTService Accounts Access Denied starting services

    We have an SQL Server 2012 SP1 which was running perfectly until we applied the SQL Server 2012 SP2.
    After SP2 was installed and the server rebooted all the associated SQL services that uses NTService\xxxxxxx accounts failed to start with Error 5: Access Denied.
    We were able to change the services to Local System account but I just want to understand why this occurred and is this ok?
    Has anyone had a similar issue or can anyone assist with an explanation?

    Hi Giulio,
    Based on your description, I tested the scenario as yours. After applying SQL Server 2012 SP2, I reboot the server , then restart all the associated SQL Server services that use NT SERVICE\<SERVICENAME> accounts successfully.
    According to the error message, it might be caused by that NT SERVICE\<SERVICENAME> accounts don’t have sufficient permissions to access the SQL Server services installation folders. You can post detailed information in the SQL Server Errorlog file
    for analysis.
    In addition, Local System is a very high-privileged built-in account. It has extensive privileges on the local system and acts as the computer on the network. And it is not recommend to use local system account for running SQL Server services. For more details
    about configuring SQL Server Service accounts, you can review the following links.
    Configure Windows Service Accounts and Permissions:
    http://msdn.microsoft.com/EN-US/library/ms143504.aspx#Windows
    Best Practices For Using SQL Server Service Accounts:
    http://blogs.technet.com/b/canitpro/archive/2012/02/08/the-sql-guy-post-15-best-practices-for-using-sql-server-service-accounts.aspx
    Thanks,
    Lydia Zhang

  • 'Access denied' when attempting to build/burn DVD, please help, urgent/desperate!

    Recently bought CS3, overjoyed with most of it. Encore is giving me serious trouble though at the moment! The problem is that it simply will not burn to a dual layer disc! When we try to burn it to disc it begins the process, wizzing through different elements, then when it gets to 'sorting files'it stops with the message 'Access Denied' If we split the Wedding video in half it will burn to a standard DVD, but it will not burn to dual layer.We installed an additional, external writer in case the problem was with the hardware, but again it would not burn to dual layer. We attempted to build the dvd as an 'image' to the harddrive to then burn to dual layer through nero. This worked for a much smaller file, but when we tried to burn the larger file to the harddrive as an Image, 'Access Denied'!! We've tried everything we can think of, ...but if anyone else can think of a way to fix this, please let us know as we are in the final stages of the video project for a client and simply cannot get the project onto disc! When we 'check project', there are no errors listed. We've tried transcoding it to 7gb 1pass, and importing it from Premire pro without transcoding it, thereby letting Encore set the settings, but no joy. Thanks, Justin.

    Rather than disabling UAC (or turning it down in Win7), just run Encore as Administrator.  Right-click, and select Run As Administrator.  Works fine for me in Windows 7 Professional 64 bit.  Doing it this way you still get the benefits of UAC.

  • Access denied. When trying to upload files into SharePoint with PowerShell

    AM trying to upload a bunch of files into SharePoint using PowerShell. I have a code that works on my local machine, but when I get on the server, it does not. Here is what my block of code looks like
    $webUrl = "http://SampleSite"
    $libraryName = "My Lib"
    $docLibraryUrlName = "My%20ContentType"
    $fileLocation = "C:\test\"
    $contentType = "My ContentType"
    #Open web and library
    $web = Get-SPWeb $webUrl
    $docLibrary = $web.Lists[$libraryName]
    $files = ([System.IO.DirectoryInfo] (Get-Item $fileLocation)).GetFiles()
    ForEach($file in $files)
    #Open file
    $fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()
    # Gather the file name
    $FileName = $File.Name
    #remove file extension
    $NewName = [IO.Path]::GetFileNameWithoutExtension($FileName)
    #split the file name by the "-" character
    $FileNameArray = $NewName.split("_")
    #Add file
    #$folder = $web.getfolder($docLibraryUrlName)
    $folder = $web.getfolder($docLibrary)
    write-host "Copying file " $file.Name " to " $folder.ServerRelativeUrl "..."
    $spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, $fileStream, $true)
    $spItem = $spFile.Item
    #populate metadata
    $spItem["First Column"] = $FileNameArray[0]
    $spItem["Second Column"] = $FileNameArray[1]
    $spItem.Update()
    $fileStream.Close();
    Again, this code works fine on my local machine but doesn't when I move this to the server. When I step through the code, I noticed that when I look at the data returned for my $folder variable in this snippet
    $folder = $web.getfolder($docLibrary)
    It shows the EffectiveRawPermissions to be "Open, BrowseUserInfo, UserClientIntegration" on the server...however, the EffectiveRawPermissions on my local machine is "FullMask". Does this have any effect on the ability of my code to be
    able to upload the files into SP on the server? I have never run into this issue, so am not sure how this makes sense...so I really appreciate any insight. Thanks
    I am getting this error when the code attempts to perform the "Add" function...
    Exception calling "Add" with "3" argument(s): "<nativehr>0x80070005</nativehr><nativestack></nativestack>Access denied."
    At C:\PowerShellScripts\tester.ps1:70 char:3
    +         $spFile = $folder.Files.Add($folder.Url + "/" + $File.Name, $fileStream, $true ...
    +         ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        + CategoryInfo          : NotSpecified: (:) [], MethodInvocationException
        + FullyQualifiedErrorId : UnauthorizedAccessException
     ...Please help

    RunWithElevatedPriv basically impersonates the webapp's app pool account, which should have full control over the entire webapp... this would work, but is not recommended for several reasons:
    - first and foremost, you shouldn't NEED to bypass the SP security model
    - second and still important, the app pool may be hosting other webapps as well, so the risk of a bug causing security-related problems within the RunWithElev codeblock is no longer scoped to the current webapp, but also other webapps that share the same
    app pool account.
    - third, same as number two, but for service accounts, and possibly even the farm... not a good practice, but a lot of SP installs aren't configured correctly, so the entire farm may be using one account... now, the RunWithElev is not just a webapp admin,
    not just a multiple webapp admin, but may be able to affect service apps, or possibly the entire farm.
    - fourth, the audit info (created by, modified by) will reference the system account, instead of your account... not a very accurate audit trail in that case.
    If you have a legit need to add the files, you should be able to get the necessary permissions (which is basically just contribute within the library / folder) easily enough.
    Scott Brickey
    MCTS, MCPD, MCITP
    www.sbrickey.com
    Strategic Data Systems - for all your SharePoint needs

  • Access Denied error with basic XML file operations

    Hi,
    I'm trying to set up a basic read, write and delete code for XML files which I can build upon in the future. The three methods are bound to three buttons on the page and all three calls are awaited. Here's my code:
    Write:
    XElement uservarnodes = new XElement("uservars",
    new XElement("uservar1", "1"),
    new XElement("uservar2", "2"),
    new XElement("uservar3", "3"),
    new XElement("uservar4", "4"),
    new XElement("uservar5", "5"),
    new XElement("uservar6", "6"),
    new XElement("uservar7", "7"),
    new XElement("uservar8", "8"));
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync("uservarfile.xml", CreationCollisionOption.ReplaceExisting);
    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    using (var outputStream = stream.GetOutputStreamAt(0))
    DataWriter mydataWriter = new DataWriter(outputStream);
    mydataWriter.WriteString(uservarnodes.ToString());
    await mydataWriter.StoreAsync();
    await outputStream.FlushAsync();
    Read (outputs the data to a textblock):
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.GetFileAsync("uservarfile.xml");
    string readtext = await Windows.Storage.FileIO.ReadTextAsync(file);
    XElement uservarnodes = XElement.Parse(readtext);
    txtTarget.Text = uservarnodes.ToString();
    Delete:
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.GetFileAsync("uservarfile.xml");
    await file.DeleteAsync(StorageDeleteOption.PermanentDelete);
    When I tap each of the buttons once it all seems to work. But when I tap any of the buttons again within the same debug session I get an Access denied exception (E_ACCESSDENIED). Other people with this error had to await when calling their method, but I'm
    already doing that: private async void btnWrite_Click(object sender, RoutedEventArgs e) { await WriteToXMLFile(); }, etc.
    And the intervals between my taps isn't that short that you'd expect that the previously called method still had not finished completing. I don't understand why I'm getting the access denied error.
    Related to my question: I have added XML to the File Type Associations, File Open Picker and File Save Picker in the appxmanifest, but somewhere I read that you do not need to do this if you're working with local app data only. Is this true?

    var stream = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
    I think because of your file stream hasn't been closed.
    by the way, it can be easier  by using System.IO.OpenStreamForWriteAsync extension method
    async public static Task<bool> SaveTextFileAsync(string filename, string data)
    byte[] fileBytes = System.Text.Encoding.UTF8.GetBytes(data);
    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
    var file = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    try
    using (var s = await file.OpenStreamForWriteAsync())
    s.Write(fileBytes, 0, fileBytes.Length);
    return true;
    catch
    return false;
    (need using System.IO namespace)
    在現實生活中,你和誰在一起的確很重要,甚至能改變你的成長軌跡,決定你的人生成敗。 和什麼樣的人在一起,就會有什麼樣的人生。 和勤奮的人在一起,你不會懶惰; 和積極的人在一起,你不會消沈; 與智者同行,你會不同凡響; 與高人為伍,你能登上巔峰。

Maybe you are looking for

  • How to know which bit version (32 or 64 bit) of jdk

    hi, i have installed java in my system and i would like to know whether it is 32 bit platform or 64 bit plaform of jdk. by using java -version we can know the jdk version ,in the same way do we have any command to know the bit version ? could you ple

  • Help with a project

    Here is my problem: In my place we have a number of copiers and every month every station has to send me the meters of their copier. For the Stations I have a form with the fields below: DDList>Items:StationA-StationB-StationC                        

  • I can find gunzip utility in solaris 2.6

    Hi, when i issue find . -name gunzip -print command in my solaris 2.6. I cant find it. how can i add gunzip back to my platform? Jeff

  • Able to select resolution in Windows?

    Hello, I spent 2 days working through boot camp issues and finally got it installed.  The reason I wanted to install it is because I wanted to play some games that only come on PC - especially Star Citizen.  When I play the game, its PAINFULLY MISERA

  • Mixed-family problem

    My husband uses a Windows 7 laptop and a digital projector to do still slideshows on the dive boats we frequent. This would also be the best way to show my HD underwater videos to other divers. His PC will connect (via 400 FW) to my Mac-formatted G-r