本文整理汇总了C#中TemporaryFile类的典型用法代码示例。如果您正苦于以下问题:C# TemporaryFile类的具体用法?C# TemporaryFile怎么用?C# TemporaryFile使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
TemporaryFile类属于命名空间,在下文中一共展示了TemporaryFile类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ConvertCsvToExcel_MicrosoftOfficeInteropExcel
public void ConvertCsvToExcel_MicrosoftOfficeInteropExcel()
{
StringBuilder content = new StringBuilder();
content.AppendLine("param1\tparam2\tstatus");
content.AppendLine("0.5\t10\tpassed");
content.AppendLine("10\t20\tfail");
using (TemporaryFile xlsxFile = new TemporaryFile(".xlsx"))
{
Clipboard.SetText(content.ToString());
Microsoft.Office.Interop.Excel.Application xlexcel;
Microsoft.Office.Interop.Excel.Workbook xlWorkBook;
Microsoft.Office.Interop.Excel.Worksheet xlWorkSheet;
object misValue = System.Reflection.Missing.Value;
xlexcel = new Microsoft.Office.Interop.Excel.Application();
// for excel visibility
//xlexcel.Visible = true;
// Creating a new workbook
xlWorkBook = xlexcel.Workbooks.Add(misValue);
// Putting Sheet 1 as the sheet you want to put the data within
xlWorkSheet = (Microsoft.Office.Interop.Excel.Worksheet) xlWorkBook.Worksheets.get_Item(1);
// creating the range
Microsoft.Office.Interop.Excel.Range CR = (Microsoft.Office.Interop.Excel.Range) xlWorkSheet.Cells[1, 1];
CR.Select();
xlWorkSheet.Paste(CR, false);
xlWorkSheet.SaveAs(xlsxFile.FileName);
xlexcel.Quit();
Console.WriteLine("Created file {0}", xlsxFile.FileName);
}
}
示例2: Constructor_Empty_FileNameExtensionTmp
public void Constructor_Empty_FileNameExtensionTmp()
{
using (var temporaryFile = new TemporaryFile())
{
Assert.That(Path.GetExtension(temporaryFile.FileName), Is.EqualTo(".tmp"));
}
}
示例3: TestExportFeeds
public void TestExportFeeds()
{
using (var feedFile1 = new TemporaryFile("0install-unit-tests"))
using (var feedFile2 = new TemporaryFile("0install-unit-tests"))
{
var feedCacheMock = CreateMock<IFeedCache>();
feedCacheMock.Setup(x => x.GetPath(FeedTest.Sub1Uri)).Returns(feedFile1);
feedCacheMock.Setup(x => x.GetPath(FeedTest.Sub2Uri)).Returns(feedFile2);
var signature = new ValidSignature(123, new byte[0], new DateTime(2000, 1, 1));
feedCacheMock.Setup(x => x.GetSignatures(FeedTest.Sub1Uri)).Returns(new OpenPgpSignature[] { signature });
feedCacheMock.Setup(x => x.GetSignatures(FeedTest.Sub2Uri)).Returns(new OpenPgpSignature[] { signature });
var openPgpMock = CreateMock<IOpenPgp>();
openPgpMock.Setup(x => x.ExportKey(signature)).Returns("abc");
_target.ExportFeeds(feedCacheMock.Object, openPgpMock.Object);
string contentDir = Path.Combine(_destination, "content");
FileAssert.AreEqual(
expected: new FileInfo(feedFile1),
actual: new FileInfo(Path.Combine(contentDir, FeedTest.Sub1Uri.PrettyEscape())),
message: "Feed should be exported.");
FileAssert.AreEqual(
expected: new FileInfo(feedFile2),
actual: new FileInfo(Path.Combine(contentDir, FeedTest.Sub2Uri.PrettyEscape())),
message: "Feed should be exported.");
File.ReadAllText(Path.Combine(contentDir, "000000000000007B.gpg")).Should()
.Be("abc", because: "GPG keys should be exported.");
}
}
示例4: Constructor_Empty_FileExists
public void Constructor_Empty_FileExists()
{
using (var temporaryFile = new TemporaryFile())
{
Assert.That(File.Exists(temporaryFile.FileName), Is.True);
}
}
示例5: Execute
public void Execute(BoostTestRunnerCommandLineArgs args, BoostTestRunnerSettings settings, IProcessExecutionContext executionContext)
{
var fixedArgs = args;
if (args != null)
{
// Adapt a copy of the command-line arguments to avoid changing the original
fixedArgs = AdaptArguments(args.Clone());
}
using (var stderr = new TemporaryFile(IsStandardErrorFileDifferent(args, fixedArgs) ? fixedArgs.StandardErrorFile : null))
{
this.Runner.Execute(fixedArgs, settings, executionContext);
// Extract the report output to its intended location
string source = (fixedArgs == null) ? null : fixedArgs.StandardErrorFile;
string destination = (args == null) ? null : args.ReportFile;
if ((source != null) && (destination != null))
{
try
{
ExtractReport(source, destination, string.IsNullOrEmpty(stderr.Path));
}
catch (Exception ex)
{
Logger.Exception(ex, "Failed to extract test report from standard error [{0}] to report file [{1}] ({2})", source, destination, ex.Message);
}
}
}
}
示例6: CompileCSharp
/// <summary>
/// Compiles a string of C# code using the newest C# compiler available on the system.
/// </summary>
/// <param name="compilerParameters">The compiler configuration (e.g. output file path).</param>
/// <param name="code">The C# code to compile.</param>
/// <param name="manifest">The contents of the Win32 manifest to apply to the output file. Will only be applied if a C# 3.0 or newer compiler is available.</param>
public static void CompileCSharp([NotNull] this CompilerParameters compilerParameters, [NotNull, Localizable(false)] string code, [NotNull, Localizable(false)] string manifest)
{
#region Sanity checks
if (compilerParameters == null) throw new ArgumentNullException(nameof(compilerParameters));
if (string.IsNullOrEmpty(code)) throw new ArgumentNullException(nameof(code));
if (string.IsNullOrEmpty(manifest)) throw new ArgumentNullException(nameof(manifest));
#endregion
// Make sure the containing directory exists
string directory = Path.GetDirectoryName(Path.GetFullPath(compilerParameters.OutputAssembly));
if (!string.IsNullOrEmpty(directory) && !Directory.Exists(directory)) Directory.CreateDirectory(directory);
using (var manifestFile = new TemporaryFile("0install"))
{
File.WriteAllText(manifestFile, manifest);
var compiler = GetCSharpCompiler(compilerParameters, manifestFile);
var compilerResults = compiler.CompileAssemblyFromSource(compilerParameters, code);
if (compilerResults.Errors.HasErrors)
{
var error = compilerResults.Errors[0];
if (error.ErrorNumber == "CS0016") throw new IOException(error.ErrorText);
else throw new InvalidOperationException("Compilation error " + error.ErrorNumber + " in line " + error.Line + Environment.NewLine + error.ErrorText);
}
}
}
示例7: Constructor_Empty_FilePlacedIntoTemporaryFolder
public void Constructor_Empty_FilePlacedIntoTemporaryFolder()
{
using (var temporaryFile = new TemporaryFile())
{
Assert.That(Path.GetDirectoryName(temporaryFile.FileName) + @"\", Is.EqualTo(Path.GetTempPath()));
}
}
示例8: DownloadResult
public DownloadResult( ILog logger, Stream zipContent )
{
File = new TemporaryFile( ".zip" );
using( zipContent )
using( var sw = System.IO.File.Open( File.Path, FileMode.Open ) )
zipContent.CopyTo( sw );
try
{
// open the zip file
using( ZipFile zip = ZipFile.Read( File.Path ) )
{
var manifestEntry = zip.Where( z => z.FileName == "manifest.xml" ).FirstOrDefault();
if( manifestEntry != null )
{
var ms = new MemoryStream();
manifestEntry.Extract( ms );
try
{
Manifest = HelpManifestData.Deserialize( ms );
}
catch( Exception ex )
{
logger.Error( "Unable to parse manifest", ex );
throw;
}
}
}
}
catch( Exception ex )
{
logger.Error( "Unable to read downloaded help content as a zip file", ex );
throw;
}
}
示例9: Activation
public override void Activation()
{
base.Activation();
m_prevActive = false;
string report = Exec("pfctl -si");
if (report.IndexOf ("denied") != -1)
throw new Exception("Permission denied.");
else if (report.IndexOf ("Status: Enabled") != -1)
m_prevActive = true;
else if (report.IndexOf("Status: Disabled") != -1)
m_prevActive = false;
else
throw new Exception("Unexpected PF Firewall status");
if (m_prevActive == false) {
string reportActivation = Exec ("pfctl -e");
if (reportActivation.IndexOf ("pf enabled") == -1)
throw new Exception ("Unexpected PF Firewall activation failure");
}
m_filePfConf = new TemporaryFile("pf.conf");
OnUpdateIps();
if (m_prevActive == false)
{
Exec("pfctl -e");
}
}
示例10: ShouldApplyDeltaToPreviousPackageToCreateNewPackage
public void ShouldApplyDeltaToPreviousPackageToCreateNewPackage()
{
using (var basisFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0.0")))
using (var signatureFile = new TemporaryFile(basisFile.FilePath + ".octosig"))
{
var signatureResult = Invoke(OctoDiff()
.Action("signature")
.PositionalArgument(basisFile.FilePath)
.PositionalArgument(signatureFile.FilePath));
signatureResult.AssertZero();
Assert.That(File.Exists(signatureFile.FilePath));
using (var newFile = new TemporaryFile(PackageBuilder.BuildSamplePackage("Acme.Web", "1.0.0.1", true)))
using (var deltaFile = new TemporaryFile(basisFile.FilePath + "_to_" + NewFileName + ".octodelta"))
{
var deltaResult = Invoke(OctoDiff()
.Action("delta")
.PositionalArgument(signatureFile.FilePath)
.PositionalArgument(newFile.FilePath)
.PositionalArgument(deltaFile.FilePath));
deltaResult.AssertZero();
Assert.That(File.Exists(deltaFile.FilePath));
var patchResult = ApplyDelta(basisFile.FilePath, basisFile.Hash, deltaFile.FilePath, NewFileName);
patchResult.AssertZero();
patchResult.AssertOutput("Applying delta to {0} with hash {1} and storing as {2}", basisFile.FilePath,
basisFile.Hash, Path.Combine(DownloadPath, NewFileName));
patchResult.AssertServiceMessage(ServiceMessageNames.PackageDeltaVerification.Name);
}
}
}
示例11: Verify
/// <inheritdoc/>
public IEnumerable<OpenPgpSignature> Verify(byte[] data, byte[] signature)
{
#region Sanity checks
if (data == null) throw new ArgumentNullException(nameof(data));
if (signature == null) throw new ArgumentNullException(nameof(signature));
#endregion
string result;
using (var signatureFile = new TemporaryFile("0install-sig"))
{
File.WriteAllBytes(signatureFile, signature);
result = new CliControl(HomeDir, data).Execute("--batch", "--no-secmem-warning", "--status-fd", "1", "--verify", signatureFile.Path, "-");
}
string[] lines = result.SplitMultilineText();
// Each signature is represented by one line of encoded information
var signatures = new List<OpenPgpSignature>(lines.Length);
foreach (var line in lines)
{
try
{
var parsedSignature = ParseSignatureLine(line);
if (parsedSignature != null) signatures.Add(parsedSignature);
}
#region Error handling
catch (FormatException ex)
{
// Wrap exception since only certain exception types are allowed
throw new IOException(ex.Message, ex);
}
#endregion
}
return signatures;
}
示例12: ShouldFindOneEarlierPackageVersion
public void ShouldFindOneEarlierPackageVersion()
{
using (var acmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, packageVersion)))
{
var destinationFilePath = Path.Combine(downloadPath,
Path.GetFileName(acmeWeb.FilePath) + "-" + Guid.NewGuid());
File.Copy(acmeWeb.FilePath, destinationFilePath);
using (var newAcmeWeb = new TemporaryFile(PackageBuilder.BuildSamplePackage(packageId, newpackageVersion)))
{
var result = FindPackages(packageId, newpackageVersion, newAcmeWeb.Hash);
result.AssertZero();
result.AssertOutput("Package {0} version {1} hash {2} has not been uploaded.", packageId, newpackageVersion,
newAcmeWeb.Hash);
result.AssertOutput("Finding earlier packages that have been uploaded to this Tentacle");
result.AssertOutput("Found 1 earlier version of {0} on this Tentacle", packageId);
result.AssertOutput(" - {0}: {1}", packageVersion, destinationFilePath);
result.AssertServiceMessage(ServiceMessageNames.FoundPackage.Name, Is.True,
new Dictionary<string, object>
{
{"Metadata.Id", packageId},
{"Metadata.Version", packageVersion},
{"Metadata.Hash", acmeWeb.Hash},
{"FullPath", destinationFilePath}
});
}
}
}
示例13: Deploy
private static TemporaryFile Deploy(Stream stream)
{
var tempFile = new TemporaryFile("0install-unit-tests");
using (var fileStream = File.Create(tempFile))
stream.CopyTo(fileStream);
return tempFile;
}
示例14: MatchingFile
public void MatchingFile()
{
using (var file = new TemporaryFile())
{
Assert.IsTrue(filter.IsMatch(file.FileInfo, environment));
}
}
示例15: NonMatchingFile
public void NonMatchingFile()
{
using (var file = new TemporaryFile())
{
file.Contents = "01234";
Assert.IsFalse(filter.IsMatch(file.FileInfo, environment));
}
}