C#进程无法访问另一个进程使用的文件。如何解决这个问题?

时间:2014-01-22 09:41:26

标签: c# http streamreader xmldocument

我已发布完整的参考代码

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Diagnostics;
using System.Security.Cryptography;
using System.Net;
using System.Xml;
using System.Globalization;
using System.Web;
using System.Xml.Linq;


namespace micro
{
class Program
{
    static void Main(string[] args)
    {


        // To generate the signature
        // creating an object for the class 'SamplePinpointSignatureGenerator
        Program microsoft = new Program();
        String applicationId = "****";
        Debug.WriteLine("The application Id :" + applicationId);
        String applicationKey = "*******";
        Debug.WriteLine("The application Key :" + applicationKey);

        //Debug.WriteLine("The requested URI :" + signs);
        // GenerateSignature(signs, applicationId, applicationKey);
        // To read the information from the CSVfile

        var reader = new StreamReader(File.OpenRead("C:/Users/Administrator/Documents/Book3.csv"));
        //var reader = new StreamReader(File.OpenRead("C:/Users/Administrator/Documents/Book2.csv"));
        var listA = new List<String>();
        var listB = new List<String>();
        var listC = new List<String>();
        var listD = new List<String>();
        var listE = new List<String>();
        var listF = new List<String>();


        int linenumber = 0;

        while (!reader.EndOfStream)
        {
            string line = reader.ReadLine();
            if (!String.IsNullOrWhiteSpace(line))
            {
                linenumber++;


                String[] values = line.Split(',');
                if (linenumber > 1)
                {

                    if (values.Length > 1)
                    {
                        listA.Add(values[0]);
                        listB.Add(values[1]);
                        listC.Add(values[2]);
                        listD.Add(values[3]);
                        listE.Add(values[4]);
                        listF.Add(values[5]);

                    }
                }

            }
        }
        String path = "C:/Users/Administrator/Downloads/pinpoint1.csv";
        var w = new StreamWriter(path);
        var line1 = string.Format("AdvertiserName" + "," + "BusinessNeedNumber" + "," + "IndustryFocusNumber" + "," + "Competency" + "," + "URL" + "," + "Signauture" + "," + "SignatureURL");// + "," + "State" + "," + "City" + "," + "Country" + "," + "UniqueId" + "," + "ProfileURL");
        w.WriteLine(line1);
        w.Flush();

        String[] firstlistA = listA.ToArray();
        String[] firstlistB = listB.ToArray();
        String[] firstlistC = listC.ToArray();
        String[] firstlistD = listD.ToArray();
        String[] firstlistE = listE.ToArray();
        String[] firstlistF = listF.ToArray();
        for (int i = 0; i < firstlistD.Length; i++)
        {
            String a = firstlistA[i].Replace("\"", "");
            String b = firstlistB[i].Replace("\"", "");
            String c = firstlistC[i].Replace("\"", "");
            String d = firstlistD[i].Replace("\"", "");
            String e = firstlistE[i].Replace("\"", "");
            String fy = firstlistF[i].Replace("\"", "");

            String URLdata = d + "," + e + "," + fy;
            Debug.WriteLine(URLdata);
            Uri signs = new Uri(URLdata);
            //Debug.WriteLine("The requested URI :" + signs);
            String signature = GenerateSignature(signs, applicationId, applicationKey);
            String sig = signature.Replace("=", "%3d");
            String g = sig.Replace("/", "%2f");
            String f = g.Replace("+", "%2b");
            String q1 = String.Concat("\"", URLdata, "&sig=", f, "\"");
            String q = String.Concat(URLdata, "&sig=", f);
            Debug.WriteLine("BusinessNeedNumber :" + a + " IndustryFocusNumber :" + b + " Competency :" + c + " The URL :" + d + " : The signature URL :" + q);

            var data = string.Format(a + "," + b + "," + c + "," + signature + "," + q1);

            w.WriteLine(data);
            w.Flush();
            // Generate the XML file for information parsing
            String ab = microsoft.GenerateXML(q);
            // XmlDocument content2 = new XmlDocument();

            // content2.LoadXml(ab);

            //  content2.Save("C:/Users/Administrator/Downloads/direct.xml");

            ReadXMLfile(ab);

        }
    }
    public String GenerateXML(String q)
    {
        // Generating the XML file for reference
        // Getting the response in XML format from the URL

        Debug.WriteLine("The Http URL after URL encoding :" + q);
        Uri signs1 = new Uri(q);
        //Debug.WriteLine("The Requested URL for getting the XML data :" + re);

        WebRequest request1 = WebRequest.Create(signs1);


        HttpWebResponse response1 = (HttpWebResponse)request1.GetResponse();

        Stream receiveStream = response1.GetResponseStream();

        StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8);

        String ab = readStream.ReadToEnd();
        // Debug.WriteLine("The data :"+a);
        //XmlDocument content2 = new XmlDocument();

        // content2.LoadXml(ab);

        //  content2.Save("C:/Users/Administrator/Downloads/direct.xml");
        return ab;
    }

    public static string GenerateSignature(Uri pinpointSyndicationRequest, string applicationId, string applicationKey)
    {
        if (null == pinpointSyndicationRequest)
        {
            throw new ArgumentNullException("pinpointSyndicationRequest");
        }
        if (String.IsNullOrEmpty(applicationId))
        {
            throw new ArgumentNullException("applicationId");
        }
        if (String.IsNullOrEmpty(applicationKey))
        {
            throw new ArgumentNullException("applicationKey");
        }

        //
        // Extract the path and query from the supplied URI
        // The hash should ONLY include the page and query (scheme, host, and port are omitted).
        //
        // e.g.,
        // http://pinpoint.microsoft.com/en-US/syndicate/Partners/?view=v2010.05
        //                              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
        //
        string request = pinpointSyndicationRequest.PathAndQuery;
        //Debug.WriteLine("The path and the query of the requested URI :" + request);

        //
        // Hash the path and query
        //
        string requestHash = GenerateHashBase64(applicationKey, request);

        //
        // Build the signature
        //
        string signature = String.Format(CultureInfo.InvariantCulture, "S-{0}-{1}", applicationId, requestHash);
        //Debug.WriteLine("The signature :" + signature);
        //
        // The signature may now be appended to the URI (in the "sig=..." query param)
        // or included as an HTTP header (as "Syndication-Sig: ...").
        //
        // If the request is appended to the URI, it must be escaped first to encode
        // Base64 characters which cannot be included verbatim in the URI.
        //


        return signature;
    }

    /// <summary>
    /// Generate a Base64-encoded SHA256 HMAC of the supplied string
    /// </summary>
    /// <param name="key">Key supplied to HMAC</param>
    /// <param name="content">String to hash</param>
    /// <returns>Base64-encoded HMAC of key and content</returns>
    private static string GenerateHashBase64(string key, string content)
    {
        if (String.IsNullOrEmpty(key))
        {
            throw new ArgumentNullException("key");
        }
        if (String.IsNullOrEmpty(content))
        {
            throw new ArgumentNullException("content");
        }

        // Convert inputs to byte arrays
        byte[] keyBytes = Encoding.Unicode.GetBytes(key);
        byte[] contentBytes = Encoding.Unicode.GetBytes(content);

        // Compute the cryptographic hash
        HMACSHA256 hmac = new HMACSHA256(keyBytes);
        byte[] hash = hmac.ComputeHash(contentBytes);

        // Convert to base64
        string result = Convert.ToBase64String(hash);
        //Debug.WriteLine("the base64 hash :" + result);

        return result;
    }

    // Method to read the XML
    public static void ReadXMLfile(String ab)
    {
        //System.Threading.Thread.Sleep(10000);
        XmlDocument content2 = new XmlDocument();

            content2.LoadXml(ab);

            content2.Save("C:/Users/Administrator/Downloads/direct.xml");// The process cannot access the file 'C:\Users\Administrator\Downloads\direct.xml' because it is being used by another process.

            String path1 = "C:/Users/Administrator/Downloads/pinpoint2.csv";

         using(var w1 = new StreamWriter(path1))
        {
        // Read and parse the required information from 'direct.xml'

            var reader1 = new StreamReader("C:/Users/Administrator/Downloads/direct.xml");

            var xmlDoc1 = XDocument.Load(reader1);

            XNamespace atom = "http://www.w3.org/2005/Atom";
            XNamespace metadata = "http://schemas.microsoft.com/ado/2007/08/dataservices/metadata";
            XNamespace dataservices = "http://schemas.microsoft.com/ado/2007/08/dataservices";

            var result = xmlDoc1.Root.Elements(atom + "entry")
.Select(e => new
{
    Title = (string)e.Element(atom + "title"),
    Id = (string)e.Element(atom + "id"),
    Urls = e.Elements(atom + "link")
        .Where(l => l.Element(metadata + "inline") != null)
        .SelectMany(l => l.Element(metadata + "inline")
            .Element(atom + "feed")
            .Elements(atom + "entry")
            .Select(e1 => (string)e1.Element(atom + "content")
                .Element(metadata + "properties")
                .Element(dataservices + "Url")).Where(k => k != null)),
    City = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "City")).Where(u => u != null)),
    State = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "State")).Where(u => u != null)),
    Country = e.Elements(atom + "link")
       .Where(l => l.Element(metadata + "inline") != null)
       .SelectMany(l => l.Element(metadata + "inline")
           .Element(atom + "feed")
           .Elements(atom + "entry")
           .Select(e1 => (string)e1.Element(atom + "content")
               .Element(metadata + "properties")
               .Element(dataservices + "Country")).Where(u => u != null))
});

            foreach (var entry in result)
            {
                foreach (var sta in entry.State)
                {

                    foreach (var ci in entry.City)
                    {
                        foreach (var coun in entry.Country)
                        {
                            foreach (var url in entry.Urls)
                            {
                                Debug.WriteLine("{0},{1},{2},{3}", entry.Title, entry.Id, ci, url);

                                String uniqueId = sta + ci + coun;
                                Debug.WriteLine(uniqueId);
                                // Writing onto CSV file
                                String advertisername = entry.Title.Replace(",", "&");
                                var data = string.Format(advertisername + "," + sta + "," + ci + "," + coun + "," + uniqueId + "," + url);

                                w1.WriteLine(data);
                                w1.Flush();

                            }
                        }
                    }


                }
            } w1.Close();
            return;
        }
    }
}

}

我收到以下错误

content2.Save("C:/Users/Administrator/Downloads/direct.xml");// The process cannot access the file 'C:\Users\Administrator\Downloads\direct.xml' because it is being used by another process.

我不知道如何解决问题,c#编程新手,请在此过程中帮助我。任何帮助表示赞赏。提前谢谢。

2 个答案:

答案 0 :(得分:1)

从帖子看起来您似乎无法访问该位置。或者,如果已存在具有相同名称的文件,则其他进程正在使用该文件。您无法替换或删除正在使用的文件。

答案 1 :(得分:0)

至少对于这个问题,我在w1.close()之后使用了return1.close()。