0

ユーザーが独自の csv をアップロードするか、リストボックスに値を入力して csv を (バックグラウンドで) 作成できるページがあります。どの方法で csv を作成するかに関係なく、その csv をバイト ストリーム経由でサーバーにアップロードする必要があります。

私の問題は、csv を作成するときに、一時ファイルを作成する必要がないことです。ストリームに書き込み、アップロードのために読み戻すことができるはずです。一時ファイルの必要性をなくすにはどうすればよいですか?

動作する現在のコード(ただし、一時ファイルを使用):

try {
                string filename = DateTime.Now.ToString("MMddyyHmssf");
                filename = filename + ".csv";
                string directory = ConfigurationManager.AppSettings["TempDirectory"].ToString();
                path = Path.Combine(directory, filename);
                using (StreamWriter sw = File.CreateText(path)) {

                    foreach (ListItem item in this.lstAddEmailAddress.Items) {
                        sw.WriteLine(" , ," + item.ToString());
                    }
                }
            } catch (Exception ex) {
                string error = "Cannot create temp csv file used for importing users by email address.  Filepath: " + path + ".  FileException: " + ex.ToString();
                this.writeToLogs(error, 1338);
            }
        }
        // put here for testing the byte array being sent vs ready byte[] byteArray = System.IO.File.ReadAllBytes(path);
        myCsvFileStream = File.OpenRead(path);
        nFileLen = (int)myCsvFileStream.Length;

私が試してみました

Stream myCsvFileStream;
using (StreamWriter sw = new StreamWriter(myCsvFileStream)) {

                    foreach (ListItem item in this.lstAddEmailAddress.Items) {
                        sw.WriteLine(" , ," + item.ToString());

                    }
                }

ただし、myCsvFileStream は初期化されていないため (ストリームは静的クラスであるため)、常に null です。

csvを作成した後のデータ(バイトストリーム)の処理は次のとおりです。

byte[] file = new byte[nFileLen];
            myCsvFileStream.Read(file, 0, nFileLen);
            bool response = this.repositoryService.SaveUsers(this.SelectedAccount.Id, file, this.authenticatedUser.SessionToken.SessionId);
            myCsvFileStream.Close();

最後にStringBuilder、csv ファイルの内容を作成していました。次に、その内容のバイト配列を取得し、それを使用して共有ストリームにデータを入力しました (ユーザーが独自の CSV ファイルを入力したときは であるHttpPostedFileが、残りの呼び出し ( respositoryservices.saveusers) を介してサーバーに送信するときは同じバイトを使用するため、共有と言いました)このメソッドを介してストリーミングする)

StringBuilder csvFileString = new StringBuilder();

            sharedStreamForBatchImport = new MemoryStream();
            foreach (ListItem item in this.lstAddEmailAddress.Items) {
                csvFileString.Append(",," + item.ToString() + "\\r\\n");
            }

            //get byte array of the string
            byteArrayToBeSent = Encoding.ASCII.GetBytes(csvFileString.ToString());
            //set length for read
            byteArraySize = (int)csvFileString.Length;
            //read bytes into the sharedStreamForBatchImport (byte array)
            sharedStreamForBatchImport.Read(byteArrayToBeSent, 0, byteArraySize);
4

2 に答える 2

2

作成したいnew MemoryStream()

于 2013-09-17T17:56:37.020 に答える
0

これは、CSVファイルを書き込むために使用する関数です

    public static bool WriteCsvFile(string path, StringBuilder stringToWrite)
    {
        try
        {
            using (StreamWriter sw = new StreamWriter(path, false))         //false in ordre to overwrite the file if it already exists
            {
                sw.Write(stringToWrite);
                return true;
            }
        }
        catch (Exception)
        {
            return false;
        }
    }

stringToWrite は、そのように作成された単なる文字列です:

    public static bool WriteCsvFile(string path, DataTable myData)
    {
        if (myData == null)
            return false;
        //Information about the table we read
        int nbRows = myData.Rows.Count;
        int nbCol = myData.Columns.Count;
        StringBuilder stringToWrite = new StringBuilder();

        //We get the headers of the table
        stringToWrite.Append(myData.Columns[0].ToString());
        for (int i = 1; i < nbCol; ++i)
        {
            stringToWrite.Append(",");
            stringToWrite.Append(myData.Columns[i].ToString());
        }
        stringToWrite.AppendLine();

        //We read the rest of the table
        for (int i = 0; i < nbRows; ++i)
        {
            stringToWrite.Append(myData.Rows[i][0].ToString());
            for (int j = 1; j < nbCol; ++j)
            {
                stringToWrite.Append(",");
                stringToWrite.Append(myData.Rows[i][j].ToString());
            }
            stringToWrite.AppendLine();
        }

        return WriteCsvFile(path, stringToWrite);
    }
于 2013-09-17T18:02:00.967 に答える