c#,寻找一种解决方案来创建具有唯一文件名的文本文件和具有特定格式的文本

问题描述 投票:-1回答:1

关于。我希望大家都过得不错。

我拥有这段代码,可以创建一个具有唯一文件名的新文本文件,并在每次我监视的事件之一发生时,将具有特定格式的文本写入每个文件。


method void recordevent(string msg)     
variables:     
string filepath;     
begin     


    filepath = string.format("{0}\{1}_{2}_{3:yyyyMMddhhmmss}_{4}_{5}.txt",     
        iprimarydirectory,     
        filnamplusymtic, 
        gronam,     
        datetime.now,
        castyp,
        numtostr(price,2));

    print(filepath);
    sw = streamwriter.create(filepath);  
    sw.autoflush = true;    
    sw.writeline(msg);      
    sw.close();     
end;



if dtc=false and dtc[1]=true and lastbaronchart and barstatus( 1 ) = 2 then begin  
recordevent(

"group "+ gronam + newline +

"symbol:" + spaces(1) + symtic + spaces(1) + “ended downtrend” + spaces(1) + “case type d” + spaces(1) + numtostr(price,2)" + newline

);    
end;

((注:iprimarydirectory,filnamplusymtic,gronam,castyp只是字符串输入,我用于将文件分为不同的组。)

我正在寻找可以让我在ninjatrader平台内使用c#进行相同操作的解决方案。

  • 即,动态生成一个唯一的文本文件,每个事件具有唯一的名称。我使用几个字符串输入和变量,从年到秒的日期和时间以及市场价格来创建文件名。这是为了确保文件名是唯一的,并且还要确保文件按符号代码和事件发生的时间排序。文件对于每个事件应该是唯一的,并且在创建之后就不应对其进行修改。

  • 使用我拥有的四种文本模板(事件有四种类型)之一,根据事件的类型在文件中写入文本,并采用特定格式,将几种字符串输入和变量,空格和换行符组合在一起。

这是我到目前为止拥有的C#代码的唯一片段。


protected override void OnBarUpdate()
        {
            if(CurrentBar % 2 != 0)
                WriteFile("Hello");
        }

        private object lockObj = new object();

        private void WriteFile(string text)
        {
          // lock a generic object to ensure only one thread is accessing the following code block at a time
          lock (lockObj)
          {
              string filePath = @"C:\ntlogs\" + DateTime.Now.ToString("yyyyMMdd HHmmss") + ".txt";
              using (System.IO.FileStream file = new System.IO.FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None))
              {

                byte[] tempstring = new UTF8Encoding(true).GetBytes(text);

                file.Write(tempstring, 0, tempstring.Length);  

                // be sure to flush the buffer so everything is written to the file.
                file.Flush();

                // The "using" block implicitly closes the FileStream object,
                // giving other threads access to the file
              }
          }

我需要能够将多个字符串输入(例如gronam和filnamplusymtic)插入文件名,但是我不知道如何包括它们。我还需要在模板后面的文件中写入文本,其中包括几个字符串输入,空格和换行符,但是如果我插入+ newline +或+ spaces(1)之类的内容,则插入insde WriteFile(“ Hello”);该代码将不再编译。

非常好,如果有人有任何建议或可以向我指出有用的信息,我将非常感激。非常感谢,问候。

c#
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.