WORD document becomes blank or corrupted after being uploaded to a Document Library programmatically?

Hi everyone,
I uploaded a WORD document to a Document Library with this code:
using (SPSite currentSite = new SPSite(SPContext.Current.Site.ID))
using (SPWeb currentWeb = currentSite.OpenWeb("Departments"))
currentWeb.AllowUnsafeUpdates = true;
SPList myList = currentWeb.Lists["Commercial Agreements"];
SPDocumentLibrary myLibrary = (SPDocumentLibrary)myList;
SPFolder myFolder = myLibrary.RootFolder.SubFolders["aFolderName"];
using (Stream fStream = FileUpload1.PostedFile.InputStream)
byte[] _bytes = new byte[fStream.Length];
SPFile myFile = myFolder.Files.Add(FileUpload1.FileName, _bytes, true);
The document gets uploaded into the correct folder in the Document Library, however when I open it from SharePoint it is just a blank document. And sometimes it is corrupted and cannot be opened.
If I upload a PDF using this code, the pdf cannot be opened. It says the file is corrupted.
Any ideas?
Thank you very much for your help in advance.
Lin

Hello,
I just written sample code, please try this: (Note: This code is not tested so you might need to modify it)
Stream fStream = FileUpload1.PostedFile.InputStream;
byte[] _byteArray = new byte[fStream.Length];
fStream.Read(_byteArray, 0, (int)fStream.Length);
fStream.Close();
string _fileUrl = myFolder.Url + "/" + FileUpload1.PostedFile.FileName;
SPFile file = myFolder.Files.Add(_fileUrl, _byteArray, true);
http://www.c-sharpcorner.com/blogs/4250/programatically-add-file-in-folder-in-sharepoint-document-li.aspx
http://sharepointwings.blogspot.sg/2013/08/programmatically-addupload-file-to.html
Hope it could help
Hemendra:Yesterday is just a memory,Tomorrow we may never see
Please remember to mark the replies as answers if they help and unmark them if they provide no help

Similar Messages

  • How to create a managed metadata column in sharepoint document library programmatically

    Hi,
    I want to create a column of type "Managed metadata" in a document library.
    I am new to managed metadata and its basics. So i need to know what it requires to create it. i got this
    1. Create a term set Group.
    2. Create term set.
    3. Create a term.
    I am using sharepoint foundation where "Term Store Management" service is not available.
    I am writing this code for OFFICE 365. So can write a code with prediction, assuming i have basic info required to run my code?
    var termStore = session.TermStores["Managed Metadata"];
    var group = termStore.Groups.GetByName("KB Submission Policy");
    var termSet = group.TermSets["KB"];
    Can write this code with respect to screen shot as follows in my term store 
    Please reply...

    Hi,
    Please check this
    http://community.bamboosolutions.com/blogs/sharepoint-2010/archive/2011/08/03/sharepoint-2010-cookbook-programmatically-create-term-sets-amp-metadata-columns-in-managed-metadata-service.aspx
    Please remember to click 'Mark as Answer' on the answer if it helps you

  • My iPhone 6 is full even though my photos are being uploaded to iCloud Photo Library.  Any recent photos are no longer being uploaded.

    My iPhone 6 is full.  I have iCloud Photo Library enabled.  Any recent photos are no longer being uploaded and are just drawing down my storage.  I have "Optimize Phone Storage" enabled.

    Open Activity monitor in Utilities, go to the CPU tab>All Processes, and note any process that would appear to be related to importing photos, such as iPhoto, and use Force Quit. This may only be a temporary fix, as it may start all over again when you reboot. If that happens, we need to do some more investigating.
    Also, close all open Applications, then open Terminal in Utilities and copy/paste and hit return, then post the output of this command.
    lsof -l +L -R -V | grep /

  • Only 33 of my 1850 photos are being uploaded to iCloud photo library ?

    When I activate iCloud photo library Beta only 33 of my 1850 photos are being uploaded, I currently sync my photos between my MBA, iPhone 6 and iPad Air
    with iTunes. All photos are deleted from my iPhone so I have to re-sync with iTunes to put them back on, I have tried uploading 3 time but it is always the same
    33 photos that get uploaded !

    Force quit - apple Menu ==> force quit
    LN

  • IPhone 6 iOS 8.1 - Photos blank / preview corrupt after restore from backup

    Hello,
    I just restored from a recent backup of an iPhone 5s @iOS 8.1 (from today) to a new iPhone 6, also on iOS 8.1.
    Everything else is ok, except the photo library. Only those images that have been edited within in iPhone 5s stock photos app over the last few months do not show up in the iPhone 6 library. The total number of images, videos etc shows up as exactly the same on both devices.
    In thumbnail view, they're just white boxes. When I click on the white thumbnail, I can see the intended image for less than a second before it turns into a blank white image again. Interestingly, if I try and revert the image to its original version (as clicked by the iPhone 5s, before it was edited in-app), the image becomes viewable again.
    I could do this if it were just a few images, but there are far too many of these scattered around in my photo library for this approach to be convenient.
    I have tried restoring from the same back up again, no luck. I even deleted the backup from iTunes, made a fresh back up of the iPhone 5s and tried restoring to the iPhone 6 - no luck.
    Is there anyway to force rebuild the photo library? Will that help?
    Or should I delete all data and settings from the iPhone 6 and start over again ?
    Any clues?

    OK I was able to fix the issue.
    Just in case this helps anyone:
    I used iExplorer and navigated to the "PhotoData" folder. I backed up and then deleted the following data files form this folder:
    1) com.apple.photos.caches_metadata.plist
    2) PhotosAux.sqlite
    3) Photos.sqlite
    Then I quit the Photos App, hard reset the iPhone and reopened the Photos App. It took a while to rebuild the photo library, but everything seems to be back to normal now.

  • Im getting backup corrupt after being told by apple to go to 6.1.1 due tothe known battery issues. Anyone know why this might be happening?

    Hi all, I recently went to 6.1 and immediately experienced the well publicised issue with battery drain. Rang Apple, followed their recommendations, perform backup, then wipe the phone, then set up as new on 6.1.1, drain battery to zero, then charge for 8 to 10 hours.  Then restore from backup.  Except first time doing it it said that there was not sufficient memore on the PC, (12gig is free), and now its saying itunes could not restore as either the backup is corrupt or not compatible with the iphone bing restored, thats not the case as its the same iphone.  Does anyone have any thoughts or am i in trouble!!

    If the backup is corrupt, there is nothing that can be done with that backup.
    Restore as new.
    All of your content should be in iTunes, simply sync it back.

  • Why does my CS5 Bridge gallery not appear after being uploaded?

    Hello,
    I have recently created a series of galleries built into Dreamweaver. I used <iframe> to incorporate and it previewed in the browser just fine. After uploading the gallery does not appear. Please review this site and code for any recommendations.
    www.jakgallery.com/19901999.html
    Thanks very much! Mike

    Take the Bridge created index.html page and associated files and folders and copy them to your Dreamweaver site folder, making sure not to overwite your existing index page or folders you may want to rename the Bridge Created files something els like add a 2. Then open the Bridge created index.html file with Dreamweaver, switch to code view and then select all t eh coed and copy it to your clipboard. Now open up your own Dreamweaver page or create a new page inyour Dreamweaver managed site and switch to code view, select all and paste previously copied code into it. Make sure to double check that URLs  point correctly to where your resources are making sure that wherever your photos are called in the code point to the folder and image where that particular folder is located in your site.
    someone else came up with this so if they see this I thank you.

  • Photos do not look the same after being uploaded to the web

    Hey,
    I have a problem with photos not looking the same as they do in LR when I upload them to the web.
    Is there a fix for this?

    >I now sometimes incorporate an "extra boost of saturation" in the
    work flow in anticipation of the loss of saturation when I take the save for web option in CS.
    >It is a bit arbitrary ... what is the view of the pros / experts on
    this remedy?
    This is a bad idea. The loss of saturation you see is only there on YOUR specific screen. It will not happen on other people's screens, except when they have a similar screen and graphic card as you. Other people might see much higher saturation on their screens. The point behind sRGB is that it provides an average target for the screen manufacturers. Screens cluster around it and so it is a REALLY bad idea to try to compensate for the problem in your specific screen. What you should do is refuse to use non-color managed webbrowsers as they will always lie to you. This means you have to use Firefox with the secret setting (see above) or Safari. If you use sRGB and a color-managed browser you will see what the average person sees. If you use sRGB and a color-dumb browser (i.e. IE) you will only see what you see.
    P.S. I am assuming you hardware calibrate your screen. This is essential. Even when calibrated, colors will only be right in color-managed apps.

  • OS X partition becomes corrupt after switching from Bootcamp

    So I've had to reinstall os x 10.9.1 no less than three  times this week and multiple times before in the past after switching between os x and windows 8.1. This usually happens after I've been using windows for a prolonged period then switch back to os x but it happened today after reinstalling os x from a time machine backup just yesterday. I'll switch between the two and os x becomes corrupt and begins the loading bar sequence after selecting the os x partition via the refit boot manager. I tried repairing the partition using disk utility from the repair partition and an external installation of os x 10.9.1 but every time the disk becomes corrupt and needs to be wiped and reinstalled or install a time machine backup. I've lost count of how many times I've had to do this and to make things even worse both of my external disks have become corrupt after being disconnected for two days while I sort this mess out. Does anyone else have similar issues or can locate an issue somewhere?

    Yeah I reinstalled osx 10.9.1 and installed all my apps, put everything back then used bootcamp to create a partition for windows then used wineclone to install my windows 8.1 backup. I jumped from windows > osx > windows > osx inside an hour to move around a few things and I forgot verify bootcamp after I installed the backup and that last time I booted to osx it was corrupted. I used disk utility from my external installation and the recovery partition and both times they need repaired which only came up with the backup and wipe notification window. There have been two occasions where I was able to fix the osx partition from my external osx installation and continue using osx quite perfectly but usually the partition becomes un-mountable after it fails to repair. Usually when this has happened the twenty something times before it's after a prolonged period of a few weeks using windows.
    I'm using refit boot manager and paragon NTFS 11 which may be the only software I've installed that could be corrupting the boot.
    SMART status is verified

  • How to get document library column data through Programmatically

    HI,
    I have one scenario..here i have to get the particular document library column data...Like fetching List data.
    In LIST We will do LIke this:
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                using (SPWeb web = site.OpenWeb())
                    SPList list = web.Lists["ListName"];
                    SPListItem item = list.Items.Add();              
                    item["Title"] = txtTitle.Text;
    item.update()
       But here we want to fetch  data from document library column data....
    I did following way....can any one suggest me....
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
                using (SPWeb web = site.OpenWeb())
                    SPDocumentLibrary documentLib = web.Lists["DocumentName"] as SPDocumentLibrary;
                    SPListItem items = documentLib.Items.Add();
    Thanks.....

    Hi,
    The code that you have posted is adding data to the list or document library. Do you want to add or fetch data from or to document library?
    You can refer following link for Inserting/Updating documents in document library:
    http://blogs.perficient.com/microsoft/2009/04/working-with-documents-stored-in-sharepoint-document-library-programmatically/
    For fetching data from document library, you can use following code:
    using (SPSite site = new SPSite(SPContext.Current.Site.Url))
    using (SPWeb web = site.OpenWeb())
    string documentLibName = "Doc_Lib_Name";
    SPFolder docLibrary = web.GetFolder(documentLibName);
    foreach (SPFile file in docLibrary.Files)
    var customColValue = file.Item["Custom_Column_Name"];
    Hope this helps!
    Regards, Shruti

  • How to open a hyperlink in new tab from document library

    hi,
    I have created a Document library programmatically.
    Added values to columns programmatically. One of the column contains a hyperlink.
    I need to open a new tab when a user click on that link?
    How can we do it?
    i cant add CEWP cause there may be libraries above 200 so i cant add CEWP in every lib.
    can we make it programmatically or any library seetings?

    <script src="http://code.jquery.com/jquery-1.8.0.min.js"></script>
    <script>
    $(function() {
    $('a').filter(function() {
    return this.hostname && this.hostname !== location.hostname;
    }).attr('target','_blank');
    </script>
    Place the above script in the master page.So that it is applicable for all the libraries.
    Find other solutions @:
    http://www.sharepointdiary.com/2011/02/sharepoint-link-list-open-in-new-window_21.html#ixzz2I939sGDr

  • Cross references corrupted after placing Word document into an InDesign document

    I am placing a word document which contains cross references to headers and captions/figures within the document. They seem to be fine and function correctly in the Word document, however, after I place this word doc into my InDesign doc, I take a look at the cross references panel and notice that the cross references have been corrupted. It is wrapping the wrong portions of text from the cross reference destinations. See screenshot for a visual of how the cross references are malformed. For example the 7th cross reference in the list should say Framework Details, not "Framework Detai
    InDesign Cross References Panel - showing malformed bits of text
    Another visual of this issue can be seen if I view the text frame in Story Editor view, see below. You can see that the cross reference source tags (blue arrow like symbols) are wrapped around the wrong portions of text. The blue tags shoud be wrapped around Framework Details and 52
    InDesign Story Editor
    You can see below as to why I think the cross references are fine in the Word doc, you can see the same cross reference I used in the example above in the word doc and it is wrapping the correct portion of text:
    Word - showing cross reference is formed corerctly
    Why is this not being maintained after placing this file into InDesign?
    Also I am not performing any cross reference updates after I import, this problem occurs immediately after the place of the doc.
    Why would InDesign be having difficulty in importing these cross references? I have set up a simple test Word document with cross references to headers and figures in and they have imported fine. What could be wrong with this other particular word doc that would be causing this "corruption" of cross references? This is not only causing my cross references to break visually and lack the update capability but also I cannot export the InDesign doc to an ePub as it keeps crashing. I believe from my reading on the web that if there is only one broken cross reference source i.e. the cross reference destination that it is trying to link to is missing, then the export to epub will fail. So this is causing a massive headache for me at the minute.
    Is there anything I could be looking at in the Word doc to try and figure out why the porblem is occuring in the first place?
    If anyone has any tips or a possible solution to this I would really appreciate it. Even better if someone knows the reason why this is happening I can tackle it from the source and prevent it happening time and time again.
    Thanks, Dave

    Only bad experiences, Peter ...
    I've seen this character shifting before on numerous occasions, both with cross references and with hyperlinks. (It's especially funny with hyperlinks, 'cause you can see that the outline box shifts one character at a time per each next link...)
    The thing is it's not just limited to hyperlinks and cross refs. Dave's screenshot doesn't show bold, italics, or other local formatting, but it's a fair bet these are off by a couple of characters as well.
    Dave's experiment of making a "minimal" Word document to confirm it's a persistent bug didn't work. I found the same thing: either a document comes in fine, or everything is foo-bar right from the start. There must be some internal Word code that InDesign forgets to count as 'a character position'. Without delving into the Word file with some very advanced tools, it's anyone's guess what code that would be.
    I can only offer the one solution that works for me: in Word, remove all hyperlinks (which is what Word uses for internal links as well as for external ones) and convert all cross-references to text. Then, if the file finally imports fine, re-build them in InDesign. It's a cumbersome workaround, but slightly better (only just) than checking each reference, delete, rebuild, check next -- etc. (And with that the chance that your other text attributes are also off.)

  • I get a blank word document opening every time i reboot my iMac after upgrading to OS Lion.

    I get a blank word document opening every time i reboot my iMac after upgrading to OS Lion. ANy ideas how to get rid of it? I have uncheked everything in mu users and groups and unchecked restore windows in the general file.

    When you logout did you uncheck the Reopen windows when logging back in check box at the bottom of the logout window. 

  • Printing multiple double-sided Word documents results wrong side being used

    When printing from MS Word (Office 2004 11.2.5) several Word documents in rapid succession (so the first has not finished by the time the second has been received by the printer) in double-sided layout (as per the Print Dialog option) and the first document is an odd number of pages then instead of the final page of the first document being printed with stuff just on the first side it actually contains [incorrectly] the first page of the second document on the second side.
    That is -
    Document 1
    1-2 3-4 5-6 7
    Document 2
    1-2 3-4 5-6 7
    end up like
    1-2 3-4 5-6 7-1 2-3 4-5 6-7
    instead of
    1-2 3-4 5-6 7-blank 1-2 3-4 5-6 7-blank
    This happens when printing to both a HP Color LaserJet 4600DN (with built-in duplex unit) and a Konica-Minolta Magicolor 7300 (also with built-in duplex unit).
    The HP Color LaserJet has 160MB of RAM and a hard disk, the Konica-Minolta Magicolor has 256MB of RAM and no hard disk.
    Has anyone else seen this happen and does it happen in other programs (Microsoft being notorious for the number of bugs in Office for Mac they have).

    Hi John,
    This sounds odd as each print job would exist as a separate spool file with its own job number. If it wasn't for both machines doing the same I would have said it was the printer. But as you have said Word is a rogue when it comes to printing (and man other things). In order to get the next document printing so quickly after the previous, do you have both documents open? Also, are you using the Print icon in Word, or goinf File > Print? If you are using the icon, then I would suggest trying File > Print (or Command P ) as I have seen some strange results when the icon is used.
    I have also seen the "Collated" option cause unwanted results. Try disabling this in the Copies & Pages menu of the Print Dialog (and maybe saving a Preset with it disabled so it can be defaulted to this).
    Regards,
    Paul

  • COM object model not functioning after encrypting the word document using office extention

         After encrypting A word document using office extention, it seems like the COM object model becomes unusable. I cannot not manipulate the encrypt document through COM interface, nor can I write macro VBScript to do some operation on the docuent.
         For example, I create a word Macro with some simple code.
    Sub hi()
        Dim i As Integer
        i = ThisDocument.Fields.Count
        MsgBox i   
    End Sub
         If the document is not encrypt, then we will see a msgbox which tells us the number of bookmarks in the current document.
         Now, encrypt the word document using the office extention, running the macro code will fail with error code " 80004005" and error message:Method 'Fields' of bject 'ThisDocument' failed.
    It is very important for us to manipulate word documents through COM interface in our system, I want to know why the COM interface does not work anymore after the document is encrypted.

    I take macro script as an example to demonstrate that word COM object model cannot be used after encripted. Actually you can reproduce the same problem when you manipulate word document through COM interface using any programming language.
    For example, you can create a text document  with the following VBscript:
    set a = createobject("Word.Application")
    set doc = a.Documents.Open("E:\temp\test.docx")
    msgbox doc.Fields.count
    doc.close
    a.quit
    Save the document with ".vbs" file extention and then run it by double clicking it. it will fail if the document is encrypted using the office extention. 

Maybe you are looking for

  • Creating fonts based on pixels size

    Hi i'am still a java beginner and i am switching from .NET so anyone can help on how can I create a font based on Pixels size rather than Point Size

  • Customer Table Issue!

    Hi,    Which table contains customer payement terms, payment method details   Pls Reply.   Thanks

  • Inserting static image

    Several questions, really I normally work in PLUS. Can you insert a standard image (customer logo) using PLUS. If so, how? I have been told (or remember from the past) the only way to do this is via desktop. If so, can I access a discoverer report cr

  • How to recover data after performing a product recovery operation

    Hi there, Recently, my Toshiba computer experienced a blue screen error. I tried running the computer in safe mode and all the other modes available, but the blue screen kept appearing. I had no other choice but to run the Product Recovery CD that ca

  • Help with putting links on graphics in spry accordion

    I have a sidebar with a spry accordian. Each content area has an image in it. I want users to be able to click on the image (after the accordian is open to it) and link to another page. But I can't find anyway to attach a link to the image, inside th