SharePoint Developer Center > SharePoint Products and Technologies Forums > SharePoint - Development and Programming > trying to store images from an image library into a physical file
Ask a questionAsk a question
 

Answertrying to store images from an image library into a physical file

  • Thursday, November 05, 2009 12:16 AMmher Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    I have an image library that I want its content stored into physical files using code. I can successfully get a collection of SPFiles with the picture. Then I am using this method to write them to file system:

    foreach (SPFile file in list.Files)
                {
                    using (StreamReader rdr = new StreamReader(file.OpenBinaryStream()))
                    {
                        using (StreamWriter writer = new StreamWriter(targetFolder + "\\" + file.Name, false))
                        {
                            writer.Write(rdr.ReadToEnd());
                        }
                    }
                }

    However the result is the files are corrupted. The files have correct names and sizes. but i can't open them with any image viewer.

Answers

  • Thursday, November 05, 2009 12:58 AMShantha Kumar Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi mher,


    try the following code to store the images to the physical folder,

    foreach (SPFile file in list.Files)
    {
    byte[] binfile = file.OpenBinary();
    FileStream fstream = new FileStream(targetFolder + "\\" + file.Name, FileMode.Create, FileAccess.ReadWrite);
    fstream.Write(binfile, 0, binfile.Length);
    fstream.Close();
    }

    • Marked As Answer bymher Thursday, November 05, 2009 3:52 PM
    •  

All Replies

  • Thursday, November 05, 2009 12:41 AMPaul Lucas Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     
    What happens if you flush and close the writer?

    writer.Flush();
    writer.Close();

  • Thursday, November 05, 2009 12:58 AMShantha Kumar Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals
     Answer
    Hi mher,


    try the following code to store the images to the physical folder,

    foreach (SPFile file in list.Files)
    {
    byte[] binfile = file.OpenBinary();
    FileStream fstream = new FileStream(targetFolder + "\\" + file.Name, FileMode.Create, FileAccess.ReadWrite);
    fstream.Write(binfile, 0, binfile.Length);
    fstream.Close();
    }

    • Marked As Answer bymher Thursday, November 05, 2009 3:52 PM
    •